如何在python中运行命令,提供输入,然后读取输出

如何在python中运行命令,提供输入,然后读取输出,python,python-3.x,subprocess,Python,Python 3.x,Subprocess,我想使用子流程中的Popen 执行命令:“python3 test.py” # The following is test.py code: string = input('Enter Something') if string == 'mypassword': print('Success') else: print('Fail') 在我的程序中,我想多次执行'python3 test.py',每次都提供输入,读取输出'Success'或'Fail'并将其存储在变量中 我的

我想使用子流程中的Popen 执行命令:“python3 test.py”

# The following is test.py code:

string = input('Enter Something')
if string == 'mypassword':
    print('Success')
else:
    print('Fail')
在我的程序中,我想多次执行'python3 test.py',每次都提供输入,读取输出'Success'或'Fail'并将其存储在变量中

我的程序假定执行“python3 test.py”,如下所示:

from subprocess import Popen, PIPE

# Runs test.py
command = Popen(['python3', 'test.py'], stdin=PIPE)
# After this, it prompts me to type in the input, 
# but I want to supply it from a variable

# I want to do something like
my_input = 'testpassword'
command.supplyInput(my_input)
result = command.getOutput()

# result will have the string value of 'Success' or 'Fail'
您可以将参数stdout=PIPE添加到Popen,并使用Popen.communicate提供输入并读取输出

from subprocess import Popen, PIPE
command = Popen(['python3', 'test.py'], stdin=PIPE, stdout=PIPE)
my_input = 'testpassword\n'
result, _ = command.communicate(my_input)
有关更多详细信息,请阅读Popen.Communication的文档:

os.systemcommand用于执行命令如果我不想被提示输入,我通常会使用该命令,但我必须在输入之后使用输入。您可以将输入作为命令行参数与命令一起传递,我理解,但在这种情况下,没有命令行参数。必须首先运行该命令,然后它会提示您手动输入某些内容。为了清楚起见,test.py文件不会更改。我想修改将正确执行test.py的python程序,为其提供输入并获得输出