0

I call prometheus by using the python3 subprocess.Popen function, always reporting an error: No such file or directory. What is Problem?

my code as follow:

if __name__ == '__main__':
    
    subprocess.Popen(["pwd"])
    rs = subprocess.Popen(["./prometheus", "--help"])

the error info:

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'

It is normal when I execute prometheus directly in the directory where the script is located

(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.
....

And I try to call node_export through the script, it is also normal. So why cannot find prometheus file ?

tripleee
  • 175,061
  • 34
  • 275
  • 318
Baker
  • 71
  • 5

1 Answers1

0

My guess is the prometheus executable is in the same directory as your Python script. Please let me know if this is not True, then I can revise my solution.

What we need here is a way to locate the prometheus executable regardless where you run the script from. For that, I would use pathlib.

import pathlib
import subprocess

if __name__ == "__main__":
    executable = pathlib.Path(__file__).with_name("prometheus")
    subprocess.run([executable, "--help"])

Note

  • The expression pathlib.Path(__file__) will return the path to the current Python script.
  • The .with_name method will replace the name path with "prometheus"
Hai Vu
  • 37,849
  • 11
  • 66
  • 93
  • Shouldn't OP's program still work if Prometheus is in the `PATH` environment variable? – 5px Aug 26 '23 at 18:18
  • @Chix, no; the `./` in the OP's existing program forces only the current working directory to be used, preventing any PATH lookup. – Charles Duffy Aug 26 '23 at 18:18