Python 无法写入子进程中的标准输入
我无法在python 3.2.5中将命令传递给stdin。我尝试了以下两种方法 另外:这是一个问题的延续 当我在空闲解释器中尝试代码时,我还收到返回的96、0、85等数字,以及Python 无法写入子进程中的标准输入,python,windows,subprocess,stdin,python-3.2,Python,Windows,Subprocess,Stdin,Python 3.2,我无法在python 3.2.5中将命令传递给stdin。我尝试了以下两种方法 另外:这是一个问题的延续 当我在空闲解释器中尝试代码时,我还收到返回的96、0、85等数字,以及打印(p.communicate()[0]) 但是没有运气 当以列表形式传递参数时,不要使用shell=True stdin.write需要一个bytes对象作为参数。您尝试连接一个str communicate()将输入写入stdin并返回一个元组,其中otput为stdout和sterr,然后等待过程完成。您只能使用
打印(p.communicate()[0])
但是没有运气 - 当以列表形式传递参数时,不要使用
shell=True
需要一个stdin.write
对象作为参数。您尝试连接一个bytes
str
将输入写入communicate()
并返回一个元组,其中otput为stdin
和stdout
,然后等待过程完成。您只能使用它一次,尝试再次调用它将导致错误sterr
- 您确定要写入的行应该在stdin上传递给您的进程吗?这不应该是您试图运行的命令吗
winpexpect
或SendKeys
模块。看#!/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)
1.Shell=真值2。写:我以前解决过这个问题,但我忘了在这里写,所以现在我有字节(r'command','UTF-8')3。communicate()是给我带来最大问题的地方,我不断得到IOError:[Errno 22]无效参数错误。我只调用了它一次,我使用的格式如下:output=p.communicate(input='which the input is')[0],即使我写:print(p.communicate()[0]),它仍然会给我IOError:[Errno 22]无效参数Error4。这是我试图运行的一个命令,所以我尝试了p=Popen([r'fileLoc/uploader.exe','command'],stdout=PIPE,stdin=PIPE,stderr=stdout)和p=Popen([r'fileLoc/uploader.exe',stdout=PIPE,stdin=PIPE,stderr=stdout),当我执行p.stdout.readlines()时,我会得到相同的登录信息您尝试过
Popen吗([r'fileLoc/uploader.exe'、'-i'、'file.txt'、'-o'、'outputFolder']、…)
?对我来说似乎更合理。write
返回写入流的字节数,因此这就是您在交互式interperter会话中看到的。读取用户名/密码的程序通常设计为从终端读取,因此当您将数据发送到stdinSebastian上时,它们往往无法正常工作,而stdinSebastian是我开发的程序“我正在尝试运行,似乎已冻结。@Rohit:它可能正在等待输入。若要测试它,请不要重定向标准输出,并查看它是否在提示(输入用户名、密码等)时停止(冻结)。”.ya我尝试过不使用stdout=outfile,但它似乎仍然被冻结。我认为启动程序本身有一个错误。我的意思是,如果没有重定向,您应该能够看到子进程的输出–要找出它阻塞的位置。很遗憾,即使没有重定向,我也无法看到输出。我将在稍后介绍我出去看看是否管用,然后我会告诉你的
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()
#!/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)