`zip` works in shell but not in Python script

According to this post I'm calling the zip command using os.system() in Python.

At the command line it works:

zip -r /Backups/backups/20152011-120209{.zip,}

When I call this from a Python script (PATH is "/Backups/backups/20152011-120209")

os.system("zip -r " + PATH + "{.zip,}")

It throws:

zip error: Nothing to do! (/Backups/backups/20152011-122909{.zip,})

What am I doing wrong?

I want to zip a directory (including its content) to a zip file with the same name at the same place (a script dumps my MySQL databases to *.sql files and I want to zip the files after that).

1

1 Answer

Before getting to the problem, I'll quote Jacob Vlijm's comment under this answer (thanks for the comment and for the link):

[...] using os.system at all is a really bad idea. Outdated and deprecated. Use subprocess.call() or subprocess.Popen() intead.

Here's the first (or one of the first) deprecation proposal, dated back to 2010.

So you should really use subprocess.Popen() instead of os.system().


When you run os.system() the command is executed in Dash (/bin/sh), while when you run the command in a terminal the command is executed in Bash (/bin/bash);

Dash doesn't support brace expansion and interprets {.zip,} literally;

Run the command in Bash: change

os.system("zip -r " + PATH + "{.zip}")

to

os.system("bash -c 'zip -r " + PATH + "{.zip,}'")

Or anyway as Darael suggests FWIW passing /Backups/backups/20152011-120209{.zip,} to expand /Backups/backups/20152011-120209 to /Backups/backups/20152011-120209.zip and /Backups/backups/20152011-120209 you might as well just pass the paths directly avoiding to spawn another shell:

os.system("zip -r " + PATH + ".zip " + PATH)
11

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