文章内容
2021/2/1 17:11:47,作 者: 黄兵
FileNotFoundError: [Errno 2] No such file or directory: 'ping'
最近在使用Python subprocess 调用ping命令监控服务器可用性。
但是通过linux服务部署的时候,出现如下错误:
FileNotFoundError: [Errno 2] No such file or directory: 'ping'
没有找到ping这个文件,但是直接通过命令的方式运行python程序是没有问题的。
python app.py
没有报错。
下面是关键部分代码:
command = ['ping', '-c', str(self._packets), '-w', str(self._timeout), host_or_ip]
# run parameters: discard output and error messages
result = subprocess.run(command, capture_output=True)
if result.returncode == 0:
get_time_result = result.stdout.decode('utf-8')
return get_time_result
可以看到在command哪里直接调用系统的ping命令,没有找到文件,参考了几篇文章都没有解决问题,具体参考文章见👇
最后直接写ping命令的完成路径,修改代码之后如下:
command = ['/usr/bin/ping', '-c', str(self._packets), '-w', str(self._timeout), host_or_ip]
# run parameters: discard output and error messages
result = subprocess.run(command, capture_output=True)
if result.returncode == 0:
get_time_result = result.stdout.decode('utf-8')
return get_time_result
最后经过测试,问题解决。
一些思考:
Ubuntu服务运行环境如下写法:
Environment="PATH=/var/Service_Ping_Monitor/venv/bin"
这里没有ping命令的目录,所有才会出现没有找到文件的错误,如果修改Ubuntu服务:
Environment="PATH=/var/Service_Ping_Monitor/venv/bin:/usr/bin"
代码:
command = ['ping', '-c', str(self._packets), '-w', str(self._timeout), host_or_ip]
# run parameters: discard output and error messages
result = subprocess.run(command, capture_output=True)
if result.returncode == 0:
get_time_result = result.stdout.decode('utf-8')
return get_time_result
依然不会报错。
同时可以查看程序的运行环境,具体内容如下:
sudo cat /proc/247369/environ LANG=en_US.utf8LANGUAGE=en_US.utf8:PATH=/var/Service_Ping_Monitor/venv/bin:/usr/binHOME=/rootLOGNAME=rootUSER=rootSHELL=/bin/shINVOCATION_ID=f29c6df98dd849d189bd13f11a189956JOURNAL_STREAM=9:1272193(venv) ubuntu@VM-8-13-ubuntu:/var/Service_Ping_Monitor$
也就是说:环境中没有ping命令的目录,所以运行ping命令的时候出现了错误。
参考链接:
1、OSError: [Errno 2] No such file or directory while using python subprocess in Django
2、Python Subprocess Call with variables [duplicate]
3、Ping command not found on Ubuntu 20.04 Focal Fossa Linux
5、systemd prepending /bin to Environment PATH
黄兵个人博客原创。
转载请注明出处:黄兵个人博客 - FileNotFoundError: [Errno 2] No such file or directory: 'ping'
评论列表