Processing file paths with parentheses with Python

2019-08-15 10:32发布

问题:

The paths of the files I want to process contain parentheses in them.

path = "/dir/file (with parentheses).txt"

I'm trying to process them in Python as follows:

subprocess.call("./process %s" % path, shell=True)

However, I get the following error

/bin/sh: 1: Syntax error: "(" unexpected

How can I pass the correct string to process the proper path?

回答1:

Try this

subprocess.call('./process "%s"' % path, shell=True)

I guess problem is more with space in file name. File names with spaces in them should be enclosed in quotes like this ./process "foo bar.txt" or escaped like this ./process foo\ bar.txt.



回答2:

Don't use shell=True. It's trouble-prone (as in the OP) and enables shell injection attacks.

Do it like this:

subprocess.call(["./process", path])

If you insist on using shell=True, read the Security Considerations in the python documentation, and make sure you use shlex.quote to correctly escape all metacharacters.