我无法在python 3.2.5中将命令传递给stdin。我试过以下两种方法 另外:这个问题是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])
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()
但没有运气。
答案 0 :(得分:0)
shell=True
。stdin.write
需要bytes
个对象作为参数。您尝试连接str
。communicate()
将输入写入stdin
并返回一个输出为stdout
和sterr
的元组,并等待该过程完成。您只能使用一次,尝试再次调用它将导致错误。答案 1 :(得分:0)
winpexpect
或SendKeys
个模块。请参阅my answer to a similar quesiton that has corresponding code examples 这是一个如何使用参数启动子进程,传递一些输入,并将合并的子进程'stdout / stderr写入文件的示例:
#!/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)