Unable to write to stdin in subprocess

2019-09-16 13:07发布

问题:

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)