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

时间:2018-07-19 06:18:50

标签: 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”,每次提供输入,然后读取输出(“成功”或“失败”)并将其存储在变量中。

假定执行“ 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'

1 个答案:

答案 0 :(得分:1)

您可以将参数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.communicate的文档: https://docs.python.org/3/library/subprocess.html#subprocess.Popen.communicate