【发布时间】:2017-08-01 08:19:14
【问题描述】:
我正在尝试使用 python 脚本获取 linux 机器上的网络接口信息,即“ifconfig -a eht0”。所以我使用以下代码:
import subprocess
proc = subprocess.Popen('ifconfig -a eth0', shell=True, stdout=subprocess.PIPE)
proc.wait()
output = proc.communicate()[0]
如果我用
从终端执行脚本python myScript.py
或与
python myScript.py &
它工作正常,但是当它在没有活动 shell 的情况下从后台运行(由 crontab 启动)时,我无法获得输出。
有什么想法吗?
谢谢
【问题讨论】:
-
您如何处理
output以查看它是否有效(无论是在后台还是在活动外壳中)?您是否将其保存到文件中?如果是这样,文件是否被创建但没有内容或根本没有文件? -
如果不设置
shell=True,比如proc = subprocess.Popen(['ifconfig', '-a', 'eth0'], stdout=subprocess.PIPE),会有区别吗? -
输出被发送到远程数据库,当它从终端运行时,我可以读取数据。如果我使用
shell=False,我会收到此错误OSError: [Errno 2] No such file or directory -
如果您不使用
shell=True,您必须将命令行作为列表传递,如我之前的评论所示。 -
@PM2Ring 我已经使用列表来传递命令,它引发了这个异常
[Errno 2] No such file or directory
标签: python linux shell background subprocess