无法写入到subprocess中的标准input

我无法将命令传递给python 3.2.5中的stdin。 我已经尝试了以下两种方法另外:这个问题是前一个问题的延续。

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解释器中的代码,以及从print (p.communicate()[0])等错误时,我也得到数字,如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() 

但没有运气。

  • 当传递参数作为列表时不要使用shell=True
  • stdin.write需要一个bytes对象作为参数。 您尝试连线。
  • communicate()将输入写入stdin并返回一个元组与stdoutsterrstdout ,并等待,直到过程完成。 您只能使用一次,试图再次调用它会导致错误。
  • 你确定你正在写的行应该传递给你的过程在标准输入? 不应该是你试图运行的命令吗?
  1. 传递命令参数作为参数,而不是标准输入
  2. 该命令可能直接从控制台读取用户名/密码,而不使用子进程的标准输入。 在这种情况下,您可能需要winpexpectSendKeys模块。 看到我的答案有类似的问题,有相应的代码示例

下面是一个例子,如何用参数启动一个子进程,传递一些输入,并将合并的子进程的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)