简体   繁体   English

如何使用python子进程执行命令并响应多个输入?

[英]How to execute a command & respond to multiple inputs using python subprocess?

I am trying to understand how to execute a command/program using python subprocess module & respond to the prompt by giving input.我试图了解如何使用 python 子进程模块执行命令/程序并通过提供输入来响应提示。

Sample Program Program1.py which can take multiple input's:可以接受多个输入的示例程序 Program1.py:

arr1=[]
username = input("Enter your username1 : ")
password = input("Enter your password1 : ")
arr1.append((username,password))
username = input("Enter your username2 : ")
password = input("Enter your password2 : ")
arr1.append((username,password))
username = input("Enter your username3 : ")
password = input("Enter your password3 : ")
arr1.append((username,password))
username = input("Enter your username4 : ")
password = input("Enter your password4 : ")
arr1.append((username,password))

for item in arr1:
    print("username:",item[0],"Password:",item[1])

I have written another program called Execute_Program1.py我编写了另一个名为 Execute_Program1.py 的程序

import subprocess

proc = subprocess.Popen('python Program1.py',stdout=subprocess.PIPE,stderr=subprocess.PIPE,stdin=subprocess.PIPE,shell=True,universal_newlines=True)
print(proc.poll())
while proc.poll() is None:
    print(proc.stdout)
    proc.stdin.write('inputdata\n')

But this program is not able to execute the Program1.py.但是这个程序不能执行Program1.py。 I have read many posts related to this.我已经阅读了很多与此相关的帖子。 As per the information I have got proc.poll() return's None then the command executed by Popen is still active.根据我得到的信息 proc.poll() return's None 然后由 Popen 执行的命令仍然处于活动状态。 But my program is giving the following output:但是我的程序给出了以下输出:

None
<_io.TextIOWrapper name=4 encoding='cp1252'>

I am using Python version 3.7.4.我使用的是 Python 3.7.4 版。 Could anyone please help me with some inputs where I am doing mistake?任何人都可以帮我提供一些我做错的输入吗? Thanks in advance.提前致谢。

I could not get it to work with subprocess at this time but I wanted you to have an ASAP working solution using the os module in case you need this quickly and are not absolutely required to use the subprocess module...我目前无法让它与 subprocess 一起工作,但我希望你有一个使用 os 模块的尽快工作解决方案,以防你快速需要它并且不是绝对需要使用 subprocess 模块......

First add this line to the end of Program1.py, with no indentation, to prevent the command window from exiting before you have a chance to see the output:首先将此行添加到 Program1.py 的末尾,不要缩进,以防止命令窗口在您有机会看到输出之前退出:

input("Press <enter> to continue")

Next, replace your entire code in Execute_Program1.py with the following:接下来,将 Execute_Program1.py 中的整个代码替换为以下内容:

import os
os.system("python Program1.py 1")

This worked beautifully in Python 3.8.1 on win10pro.这在 win10pro 上的 Python 3.8.1 中运行良好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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