Command not found trying python script for bash

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.

4

3 Answers

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.

os.system() starts a shell, executes the command, and closes that shell. Your cd's effect is lost. Change directory with Python itself:

os.chdir("Downloads/smartgit")
subprocess.call(["bin/smargit.sh"])

Better yet, which chdir at all? Why not directly call the script:

smartgit_path = os.path.expanduser("~/Download/smartgit/bin/smartgit.sh")
subprocess.call([smartgit_path])
2

Why are you using Python if all you do with it is to invoke shell commands? A simple shell script would do that far easier and as long most of your Python commands make use of os.system or the subprocess module you're basically wrapping a shell script inside a Python program (with additional pitfalls) which would require you to learn some shell scripting anyway.

Here's how you can achieve the same (as far as I understand it) with a shell script:

#!/bin/sh
cd Downloads/smartgit
bin/smargit.sh

Or more simply:

Downloads/smartgit/bin/smargit.sh

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like