Ubuntu – Command not found trying python script for bash

bashcommand linepythonscripts

I am trying to run a bash command from a python script after looking at these videos (1, 2). This is my first time trying this.

My script:

import os
import subprocess

os.system("cd Downloads/smartgit")
#  os.system("cd Downloads/smartgit/bin")
#  os.system('sudo "bin/smartgit.sh"')
#  os.system("sudo bin/smartgit.sh")
#  os.system("sudo ./smartgit.sh")
#  subprocess.call("./smargit.sh", shell=True)
#  subprocess.call("sudo ./smargit.sh", shell=True)
#  subprocess.call("sudo smargit.sh", shell=True)
subprocess.call("bin/smargit.sh", shell=True)

You can see my earlier incarnations commented out. I chmod'd the file, but neither this:

malikarumi@Tetuoan2:~/Downloads/smartgit/bin$ cd ~
malikarumi@Tetuoan2:~$ python smartgit.py
sh: 1: bin/smartgit.sh: not found

Nor this:

malikarumi@Tetuoan2:~$ python smartgit.py
sudo: bin/smartgit.sh: command not found

Worked, and I don't get why, because this:

malikarumi@Tetuoan2:~$ cd Downloads/smartgit
malikarumi@Tetuoan2:~/Downloads/smartgit$ bin/smartgit.sh

does!

Thanks for helping me understand and fix this script.

Best Answer

It makes no sense to run cd commands in Python's os.system(...) function, as each of those calls spawns its own, separate shell inside which the command runs, which do not affect the main process or the shells of other function calls. Therefore the cd of one call does not affect the working directory of other calls.

You can use os.chdir(...) instead to change the working directory of your whole Python process.

However, you should not rely on implicit relative paths like this in your application, this will break if you run the script from any other location than the home directory. Maybe you want to prefix the path with ~/ to be relative to your home directory.

Related Question