2016-11-05 60 views
0

我想通過python中的命令行創建一個AVD(Android虛擬設備)。爲此,我需要將一個字符串n傳遞給stdin。我曾嘗試以下在stdin中傳遞字符串

emulator_create = str(subprocess.check_output([android,'create', 'avd', '-n', emulator_name, '-t', target_id, '-b', abi],stdin=PIPE)) 
emulator_create.communicate("n") 

,但它提出了以下錯誤

raise CalledProcessError(retcode, cmd, output=output) 
subprocess.CalledProcessError: Command '['/home/fahim/Android/Sdk/tools/android', 'create', 'avd', '-n', 'samsung_1', '-t', '5', '-b', 'android-tv/x86']' returned non-zero exit status 1 

Process finished with exit code 1 

我能做些什麼?

+1

您應該捕獲錯誤並檢查異常的'output'屬性。 –

回答

0

有些東西不適合你的例子。 subprocess.check_output()返回您要執行的子進程的輸出,而不是處理此進程的句柄。換句話說,你得到一個你不能用來操作子進程的字符串對象(或者一個字節對象)。

可能發生的是,您的腳本使用subprocess.check_output()將執行子進程並等待完成,然後再繼續。但因爲你永遠無法與之通信,它將與一個非零返回值完成,這將提高subprocess.CalledProcessError


現在,使用grep作爲標準輸入等待命令的例子執行的東西(因爲我沒有安裝Android虛擬設備的創造者做),你可以這樣做:

#!/usr/bin/env python2.7 
import subprocess 

external_command = ['/bin/grep', 'StackOverflow'] 
input_to_send = '''Almost every body uses Facebook 
You can also say that about Google 
But you can find an answer on StackOverflow 
Even if you're an old programmer 
''' 

child_process = subprocess.Popen(args=external_command, 
         stdin=subprocess.PIPE, 
         stdout=subprocess.PIPE, 
         universal_newlines=True) 
stdout_from_child, stderr_from_child = child_process.communicate(input_to_send) 
print "Output from child process:", stdout_from_child 
child_process.wait() 

這將打印「從子進程輸出:但是你可以找到關於StackOverflow的答案」,這是從grep輸出。

在這個例子中,我有

  1. 使用該類subprocess.Popen創建一個句柄子進程
    • 設置參數stdinstdout與價值subprocess.PIPE以使我們稍後溝通這個流程。
  2. 使用其.communicate()方法向其標準輸入發送字符串。在同一步驟中,我檢索了它的標準輸出和標準錯誤輸出。
  3. 印刷在上一步中檢索到的標準輸出(只是這樣表明它實際上是工作)
  4. 等了,這孩子過程完成

在Python 3.5,這是更簡單:

#!/usr/bin/env python3.5 
import subprocess 

external_command = ['/bin/grep', 'StackOverflow'] 
input_to_send = '''Almost every body uses Facebook 
You can also say that about Google 
But you can find an answer on StackOverflow 
Even if you're an old programmer 
''' 

completed_process_result = subprocess.run(args=external_command, 
              input=input_to_send, 
              stdout=subprocess.PIPE, 
              universal_newlines=True) 
print("Output from child process:", completed_process_result.stdout) 

在這個例子中,我有:

  • 使用的模塊功能subprocess.run()執行命令。
    • input參數是我們送的返回值用於以後中檢索子進程的輸出

現在你的子進程

  • 的標準輸入字符串必須根據您的情況修改此代碼。