且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

无法在子进程中写入标准输入

更新时间:2023-11-17 23:17:58

  1. 将命令参数作为参数传递,而不是作为标准输入
  2. 该命令可能会直接从控制台读取用户名/密码,而无需使用子进程的标准输入.在这种情况下,您可能需要 winpexpectSendKeys 模块.请参阅我对具有相应代码示例的类似问题的回答
  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

以下是如何使用参数启动子进程、传递一些输入以及将合并的子进程的 stdout/stderr 写入文件的示例:

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)