Problem scenario
Your Python program is trying to invoke a Bash command. But you get an error like this: "FileNotFoundError: [Errno 2] No such file or directory". What should you do?
Possible Solution #1 Use the shell=True command if your environment is secure. This is not a recommended practice from a security perspective. We have found that this with shell=True syntax can make the error go away:
subprocess.Popen(variableofcommand, shell=True)
Only do the above if you know it is ok with the systems administrator and/or programmers. Some businesses would not allow the above.
Possible Solution #2 We have found that this can happen with the Bash command is composed in a variable. If you hard code the Bash command in the subprocess.Popen(foobar) syntax (where foobar is where you place the bash command with words enclosed with double quotes and followed by commas), the command may work.
Possible Solution #3 The environment variables that the Python program may be different from what you expect. As an intermediate troubleshooting step, you may want the program to invoke something like this /bin/env > /tmp/results.txt
(provided that you have no sensitive data in the env environment variable such that the /tmp/ directory should not have). You may find that you need to use full paths to the executables of the Bash command.
Possible Solution #4 Use a Python SDK instead of the subprocess/Popen/Bash commands. Sometimes what you are trying to do will have an SDK associated with it. This option is not always feasible however; sometimes there are no SDKs for what you are trying to do.
Possible Solution #5 If you use the absolute path to the command (e.g., /usr/bin/nmap) and keep getting the error, a space in the arguments can cause the problem. The solution is to put the variable of the command into tokens in a list like this:
This format could cause the problem:comm_to_beex = ["ls -lh"]
This could fix the problem:comm_to_beex = ["ls", "-lh"]
subprocess.run(commtobex, stdout=subprocess.PIPE, text=True)
For running Bash commands with Python 3, this external page has more information.
If you want to purchase a Python book, see this page.