Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何执行交互式外部命令?_Python_Bash_Subprocess - Fatal编程技术网

Python 如何执行交互式外部命令?

Python 如何执行交互式外部命令?,python,bash,subprocess,Python,Bash,Subprocess,我通常编写bash脚本,但现在我正在用python编写一个。因此,我有一个问题,我想运行一个交互式命令,该命令要求一些用户数据,因此理想情况下,我希望将stdin、stdout的控制权传递给bash,然后在命令正确执行后返回python脚本 问题是:我还不能用操作系统来做这件事。我还想捕获我运行的命令的退出状态。请参阅@falsetru old habbit。很抱歉他们做同样的事情,所以不会对结果有太大影响。由于您仍然需要执行循环和睡眠,唯一的区别是您调用的是.poll(),而不是.wait()

我通常编写bash脚本,但现在我正在用python编写一个。因此,我有一个问题,我想运行一个交互式命令,该命令要求一些用户数据,因此理想情况下,我希望将stdin、stdout的控制权传递给bash,然后在命令正确执行后返回python脚本


问题是:我还不能用操作系统来做这件事。我还想捕获我运行的命令的退出状态。

请参阅@falsetru old habbit。很抱歉他们做同样的事情,所以不会对结果有太大影响。由于您仍然需要执行循环和睡眠,唯一的区别是您调用的是
.poll()
,而不是
.wait()
,在我看来,轮询退出代码比等待更直观。。但我想这取决于每个人:)
from subprocess import Popen, STDOUT, PIPE
from time import sleep

x = Popen('du -h', shell=True, stdout=PIPE, stdin=PIPE, stderr=STDOUT)
while x.poll() == None:
    sleep(0.25)
print('Command finished successfully with the following exit status:',x.poll())
print('And this was the output given by the command:')
print(x.stdout.read())
x.stdout.close()
x.stdin.close()