简体   繁体   中英

Unable to write to stdin in subprocess

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.

  • 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?
  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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM