无法在子进程中写入标准输入 [英] Unable to write to stdin in subprocess
本文介绍了无法在子进程中写入标准输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法在 python 3.2.5 中将命令传递给 stdin.我尝试了以下两种方法另外:这个问题是上一个问题的延续.
i am unable to pass in commands to stdin in python 3.2.5. I have tried with the following 2 approaches Also: This question is a continuation of a previous question.
from subprocess import Popen, PIPE, STDOUT
import time
p = Popen([r'fileLoc/uploader.exe'],shell = True, stdout=PIPE, stdin=PIPE, stderr=STDOUT)
p.stdin.write('uploader -i file.txt -d outputFolder\n')
print (p.communicate()[0])
p.stdin.close()
当我在 IDLE 解释器中尝试代码时,我也得到了返回给我的数字,例如 96、0、85,以及诸如来自 print (p.communicate()[0]) 的错误
代码>
i also get numbers such as 96, 0, 85 returned to me when i try the code in the IDLE interpreter, along with errors such as from the print (p.communicate()[0])
Traceback (most recent call last):
File "<pyshell#132>", line 1, in <module>
p.communicate()[0]
File "C:\Python32\lib\subprocess.py", line 832, in communicate
return self._communicate(input)
File "C:\Python32\lib\subprocess.py", line 1060, in _communicate
self.stdin.close()
IOError: [Errno 22] Invalid argument
我也用过:
from subprocess import Popen, PIPE, STDOUT
import time
p = Popen([r'fileLoc/uploader.exe'],shell = True, stdout=PIPE, stdin=PIPE, stderr=STDOUT)
p.communicate(input= bytes(r'uploader -i file.txt -d outputFolder\n','UTF-8'))[0]
print (p.communicate()[0])
p.stdin.close()
但没有运气.
推荐答案
- 将命令参数作为参数传递,而不是作为标准输入
- 该命令可能会直接从控制台读取用户名/密码,而无需使用子进程的标准输入.在这种情况下,您可能需要
winpexpect
或SendKeys
模块.请参阅我对具有相应代码示例的类似问题的回答
- Pass command arguments as arguments, not as stdin
- The command might read username/password from console directly without using subprocess' stdin. In this case you might need
winpexpect
orSendKeys
modules. See my answer to a similar quesiton that has corresponding code examples
以下是如何使用参数启动子进程、传递一些输入以及将合并的子进程的 stdout/stderr 写入文件的示例:
Here's an example how to start a subprocess with arguments, pass some input, and write merged subprocess' stdout/stderr to a file:
#!/usr/bin/env python3
import os
from subprocess import Popen, PIPE, STDOUT
command = r'fileLoc\uploader.exe -i file.txt -d outputFolder'# use str on Windows
input_bytes = os.linesep.join(["username@email.com", "password"]).encode("ascii")
with open('command_output.txt', 'wb') as outfile:
with Popen(command, stdin=PIPE, stdout=outfile, stderr=STDOUT) as p:
p.communicate(input_bytes)
这篇关于无法在子进程中写入标准输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文