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

时间:2014-02-04 13:11:23

标签: python bash subprocess

我经常编写bash脚本,但我现在正在python中编写一个。所以我有一个问题,我想运行一个交互式命令,询问一些用户数据,所以理想情况下我想将stdin,stdout的控制传递给bash,然后在命令正确执行后返回我的python脚本

问题是:我还没能用os.system做到这一点。而且我还想捕获我运行的命令的退出状态。

1 个答案:

答案 0 :(得分:1)

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()