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

2

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:

user@myuser:~ export PATH=$PATH:~/misScripts

user@myuser:~ bash scriptEcho.sh

Hello world!

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

pi@raspberrypi:~ $ 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
source

2 answers

2

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
source
0

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

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