Shell expansion in Python subprocess [duplicate]

2019-07-05 02:56发布

问题:

Possible Duplicate:
Python subprocess wildcard usage

Using the Python 2.6 subprocess module, I need to run a command on a src.rpm file that I am building with a previous subprocess call.

Unfortunately, I am working with spec files that are not consistent, so I only have a vague idea of what the filename of the src.rpm should look like (for instance, I know the name of the package and the extension in something named "{package}-{version}.src.rpm" but not the version).

I do know, however, that I will only have one src.rpm file in the directory that I am looking, so I can call mock with a command like

mock {options} *.src.rpm

and have it work in shell, but subprocess doesn't seem to want to accept the expansion. I've tried using (shell=True) as an argument to subprocess.call() but even if it worked I would rather avoid it.

How do I get something like

subprocess.call("mock *.src.rpm".split())

to run?

回答1:

Use the glob package:

import subprocess    
from glob import glob
subprocess.call(["mock"] + glob("*.src.rpm"))


回答2:

The wildcard * has to be interpreted by the SHELL. When you run subprocess.call, by default it doesn't load a shell, but you can give it shell=True as an argument:

subprocess.call("mock *.src.rpm".split(), shell=True)