2016-11-10 47 views
1

我需要實現一個外部應用程序來計算Modbus通信的CRC值。 可執行需要的輸入串並還給輸出這樣的:Python子進程.Popen無法使用標準輸出

CRC16 = 0x67ED/26605 
CRC16 (Modbus) = 0x7CED/31981 

我所說的PROGRAMM事後在輸入手動鍵入。

p = Popen(["some_file.exe", "-x"], stdin=PIPE) 
p.communicate("some_string") 

目前爲止工作正常。

但是,我想將輸出保存到一個變量或其他東西(沒有額外的文件)供進一步的使用。

我知道有輸出和錯誤的論點,但輸入

p = Popen([file, "-x"], stdin=PIPE, stdout=PIPE, stderr=PIPE) 

什麼也沒有發生在所有的時候。

有沒有人有想法該怎麼辦?

在此先感謝。

PS:在Windows 7

回答

1

使用Python 2.7要獲得LS的輸出,使用標準輸出= subprocess.PIPE。

proc = subprocess.Popen('ls', stdout=subprocess.PIPE) 
output = proc.stdout.read() 
print output 

索取:Pipe subprocess standard output to a variable

注:

如果使用標準輸入作爲PIPE你必須在這個例子中分配一個值,如:

grep = Popen('grep ntp'.split(), stdin=PIPE, stdout=PIPE) 
ls = Popen('ls /etc'.split(), stdout=grep.stdin) 
output = grep.communicate()[0] 

如果值由下式給出控制檯使用PIPE時,必須指定stdin值爲 sys.stdin

+0

感謝您的回覆。我不知道,但這似乎並不奏效。我需要給程序一個輸入,所以需要一個'stdin = PIPE'。只使用這個參數是好的,但添加'stdout = PIPE'不是。如果你使用'stdin = PIPE',你必須指定一個值給stdin,否則它將爲空。如果你使用'stdin = PIPE',那麼我可以寫入一個變量'output = ...' – mulm

+0

@mulm。 –

0

好的,我明白了。

它說,在舊的崗位: How do I write to a Python subprocess' stdin?

p.communicate()只是等待下面的表單的輸入:

p = Popen(["some_file.exe", "-x"], stdout=PIPE, stdin=PIPE, stderr=PIPE) 
output = p.communicate(input="some_string")[0] 

然後輸出具有所有接收到的信息。

相關問題