Change directory in python – os.chdir('/tmp') vs os.system("cd " + backup_location)

Question:

I’m experimenting with using Python for backups, because my Bash script became too big and complicated. I’m totally new in Python, I’m not fan of it, but it seems like Python is perfect tool for such complicated scripts.

I have found something to start with on Github:

https://github.com/Tutorialwork/Linux-Backup-Script/blob/master/backup.py

In the script above there is line like this:

os.system("cd " + config.backup_location + " && rm mysqlbackup-" + date + ".sql")

My question is:

Is there any practical difference between calling filesystem manipulation commands thru os.system("cd somedir") and functions like os.chdir("somedir")?

I’m using Python 3.9 on Debian 11. It would be good if my script could be portable between Linux distros. Windows compatybility is not required.

Asked By: Kamil

||

Answers:

Yes. There is.
When you run –

os.chdir("somedir")

The dir changes in the python context. So calling

os.getcwd()

returns the new changed dir.

When running

os.system("cd somedir")

A new process is spawn in which the directory is changed

In the example you gave, the writers wanted to do something in another process, so they changed the directory inside the spawned process.

Answered By: Shu ba
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.