2011-12-13 125 views
6

我有一個問題,我得到的錯誤,當我嘗試用Python來執行該代碼3.2.2爲stdin.write格式化字符串()在python 3.x的

working_file = subprocess.Popen(["/pyRoot/iAmAProgram"], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE) 

working_file.stdin.write('message') 

我明白了Python 3改變了它處理字符串的方式,但我不明白如何格式化'消息'。有誰知道我會如何改變這個代碼是有效的?

千恩萬謝

喬恩

更新:繼承人的錯誤消息我得到

Traceback (most recent call last): 
    File "/pyRoot/goRender.py", line 18, in <module> 
    working_file.stdin.write('3') 
TypeError: 'str' does not support the buffer interface 
+0

你忘記了錯誤信息。 –

回答

2

是您的錯誤消息 「類型錯誤: 'STR' 不支持緩衝區接口」?該錯誤消息告訴你幾乎到底是什麼錯誤。您不會將字符串對象寫入該sdtin。那麼你寫什麼?那麼,任何支持緩衝接口的東西。通常這是字節對象。

像:

working_file.stdin.write(b'message') 
7

我以前的答案一致(除了「錯誤消息告訴你到底出了什麼問題」的一部分),但我想完成它。如果情況是,你必須要寫入到管道(而不是一個字節對象)的字符串,你有兩個選擇:

1)進行編碼每個字符串將它們寫到管道第一前:

working_file.stdin.write('message'.encode('utf-8')) 

2)包住管道進入一個緩衝的文本界面,將做編碼:

stdin_wrapper = io.TextIOWrapper(working_file.stdin, 'utf-8') 
stdin_wrapper.write('message') 

(請注意,I/O現在緩衝,所以你可能需要調用stdin_wrapper.flush() )