Unable to write to stdin in subprocess

空扰寡人 提交于 2020-01-06 08:43:16

问题


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()

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

i have also used:

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()

but with no luck.


回答1:


  • don't use shell=True when passing the arguments as list.
  • stdin.write needs a bytes object as argument. You try to wire a str.
  • communicate() writes input to the stdin and returns a tuple with the otput of stdout and sterr, and it waits until the process has finished. You can only use it once, trying to call it a second time will result in an error.
  • are your sure the line you're writing should be passed to your process on stdin? Shouldn't it be the command you're trying to run?



回答2:


  1. Pass command arguments as arguments, not as stdin
  2. The command might read username/password from console directly without using subprocess' stdin. In this case you might need winpexpect or SendKeys modules. See my answer to a similar quesiton that has corresponding code examples

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)


来源:https://stackoverflow.com/questions/17329648/unable-to-write-to-stdin-in-subprocess

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!