我使用python3的subprocess.Popen函数调用prometheus,总是报错:No such file or directory。什么是问题?
我的代码如下:
if __name__ == '__main__':
subprocess.Popen(["pwd"])
rs = subprocess.Popen(["./prometheus", "--help"])
错误信息:
Traceback (most recent call last):
File "xxxe/integration_test/test.py", line 33, in <module>
rs = subprocess.Popen(["./prometheus", "--help"])
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/subprocess.py", line 951, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/subprocess.py", line 1821, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: './prometheus'
我直接在脚本所在目录执行prometheus就正常了
(venv) ➜ integration_test ./prometheus --help
usage: prometheus [<flags>]
The Prometheus monitoring server
Flags:
-h, --[no-]help Show context-sensitive help (also try --help-long and --help-man).
--[no-]version Show application version.
....
而且我尝试通过脚本调用node_export,也正常。那么为什么找不到 prometheus 文件呢?
我的猜测是
prometheus
可执行文件与 Python 脚本位于同一目录中。如果这不是真的,请告诉我,然后我可以修改我的解决方案。
我们这里需要的是一种找到 prometheus 可执行文件的方法,无论您从哪里运行脚本。为此,我将使用 pathlib。
import pathlib
import subprocess
if __name__ == "__main__":
executable = pathlib.Path(__file__).with_name("prometheus")
subprocess.run([executable, "--help"])
pathlib.Path(__file__)
将返回当前Python脚本的路径。.with_name
方法将用“prometheus”替换名称路径