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

2024-03-29 07:08:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从子进程使用Popen 执行命令:“python3”测试.py'

# The following is test.py code:

string = input('Enter Something')
if string == 'mypassword':
    print('Success')
else:
    print('Fail')

在我的程序中,我想执行'python3'测试.py'多次,每次提供输入,读取输出('成功'或'失败'),并将其存储在变量中。你知道吗

我的程序应该执行“python3”测试.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'

Tags: tofrompytest程序inputstringit
1条回答
网友
1楼 · 发布于 2024-03-29 07:08:32

您可以将参数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

相关问题 更多 >