Execute bash script, from python, with script in the PATH


I have a folder with multiple scripts that I want to call from Python.

I have added the folder to the PATH to be able to call these from any directory. And it has been added correctly:

[email protected]:~ export PATH=$PATH:~/misScripts

[email protected]:~ bash scriptEcho.sh

Hello world!

But when I try to call this from Python it tells me that the file does not exist.

[email protected]:~ $ python3
Python 3.5.3
>>> import subprocess
>>> subprocess.run(['bash','scriptEcho.sh'])
bash: scriptEcho.sh: No such file or directory
CompletedProcess(args=['bash', 'scriptEcho.sh'], returncode=127)

If subprocess is added shell = True, the interpreter closes and leaves a hanging process (which does not execute the script anyway).

Any idea why does it tell me that the file does not exist, and how to call the PATH scripts from python?

asked by Juliosor 23.08.2018 в 13:54

2 answers


Python is right because the script is not in the PATH when subprocess tries to access it. When you do $ export PATH=$PATH:~/misScripts add to PATH the directory misScripts only temporarily for that session , if you open a new terminal you will have to add it again, that's why Python can not find it.

If you want to add it to the PATH permanently you must edit the file ~/.profile or ~/.bashrc depending on your particular case, adding the line:

export PATH="$PATH:~/misScripts"

In that case subprocess.run(['bash','scriptEcho.sh']) will work without problems.

answered by 23.08.2018 / 14:15

Try putting ./ or .\ in front of the name of the script.

>>> subprocess.run(['bash','./scriptEcho.sh'])
answered by 23.08.2018 в 14:00