我想从 python 运行一个 shell 命令并使用 subprocess.Popen 接收它的输出。问题是,当我关闭进程并发送 Ctrl-C 时,我没有得到任何输出。我究竟做错了什么?代码:
>>> import subprocess
>>> sub = subprocess.Popen(["xinput", "test", "8"], stdout=subprocess.PIPE) #receive mouse events
>>> output = sub.communicate()[0].read()
^CTraceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/subprocess.py", line 693, in communicate
stdout = self.stdout.read()
KeyboardInterrupt
>>> output
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'output' is not defined
受 Jett 这篇文章的启发: