Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does python subprocess zip fail but running at shell works?

Tags:

python

shell

zip

I'm on Mac OS X using Python 2.7; using subprocess.call with zip fails yet running the same command at the shell succeeds. Here's a copy of my terminal:

$ python
Python 2.7.2 (default, Oct 11 2012, 20:14:37) 
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> subprocess.call(['zip', 'example.zip', 'example/*'])
    zip warning: name not matched: example/*

zip error: Nothing to do! (example.zip)
12
>>> quit()
$ zip example.zip example/*
  adding: example/file.gz (deflated 0%)

I've also tried with full paths and had the same result.

like image 653
Neil C. Obremski Avatar asked Oct 25 '13 08:10

Neil C. Obremski


1 Answers

Because running a command in the shell is not the same thing as running it with subprocess.call(); the shell expanded the example/* wildcard.

Either expand the list of files with os.listdir() or the glob module yourself, or run the command through the shell from Python; with the shell=True argument to subprocess.call() (but make the first argument a whitespace-separated string).

Using glob.glob() is probably the best option here:

import glob
import subprocess

subprocess.call(['zip', 'example.zip'] + glob.glob('example/*'))
like image 197
Martijn Pieters Avatar answered Oct 29 '22 09:10

Martijn Pieters