python popen raise child_exception,OSError: No such file or directory
阿新 • • 發佈:2019-02-16
問題背景
linux系統中使用python指令碼,來獲取系統ip資訊。使用了python的subprocess工具包
程式碼片段如下:
from subprocess import Popen, PIPE
def getIfconfig():
info = Popen(['ifconfig'], stdout = PIPE)
data = info.stdout.read()
return data
該部分程式碼在命令列中直接執行python指令碼,程式順利通過。
但是
當使用crontab命令將該指令碼設定成定時任務時,程式執行出錯,檢視日誌錯誤資訊:
網上查詢解決方法
- 有的是因為Popen函式第一個引數只能接受list格式資料,結果傳入了字串導致錯誤
- 有的將Popen函式的shell引數值設為True,問題解決
但我試過後都不行,仍然報錯,後來找到解決方法記錄在下
解決方法
在Popen函式中使用ifconfig的絕對路徑
查詢ifconfig的絕對路徑:linux命令列中使用命令 which ifconfig
/usr/bin/ifconfig
程式碼修改如下:
from subprocess import Popen, PIPE
def getIfconfig():
info = Popen(['/usr/sbin/ifconfig' ], stdout = PIPE)
data = info.stdout.read()
return data
定時任務順利執行,bingo!