[英]Python subprocess.Popen stdin interfering with stdout/stderr
對此感到非常困惑。 使用Popen時,如果僅使用stdout或stderr,則以下代碼有效:
def run(self):
self.externalProcess = subprocess.Popen(['./external_process.out 1>&2'], shell=True, stderr=subprocess.PIPE)
while self.externalBinary.poll() is None:
print('Still running')
print('Done running')
我使用stderr文件描述符是因為我正在GUI中實時監視進程輸出,並且stderr沒有緩沖。 請參閱我的另一個問題,以獲取有關該混亂的更多背景信息: Python逐行從子進程捕獲stdout
我在這里遇到的問題是,一旦我添加了stdin以允許將用戶輸入傳遞給外部進程,它就開始表現出好像再次緩沖了stdout:
def run(self):
self.externalProcess = subprocess.Popen(['./external_process.out 1>&2'], shell=True, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
while self.externalBinary.poll() is None:
print('Still running')
print('Done running')
我的問題是為什么stdin似乎會影響stdout和stderr?
似乎您可能正在嘗試以交互方式將數據寫入子進程(通過STDIN)以及讀取其輸出(通過STDOUT)。
正如對此SO問題的回答中所提到的,這是不可以的!
您可以使用Popen.communicate
,但這是一個阻塞調用,它將等待所有通信完成(您無法像在示例中那樣進行輪詢)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.