Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
477 views
in Technique[技术] by (71.8m points)

python - how to avoid shell=True in subprocess

I have subprocess command to check md5 checksum as

subprocess.check_output('md5 Downloads/test.txt', stderr=subprocess.STDOUT, shell=True)

It works fine. But I read try to avoid shell=True but when I run

subprocess.check_output('md5 Downloads/test.txt', stderr=subprocess.STDOUT, shell=False)

I get error OSError: [Errno 2] No such file or directory

Can I run above command or workaround with shell=False or it's ok to keep shell=True?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Just pass the arguments to check_output() as a list:

subprocess.check_output(["md5", "Downloads/test.txt"], stderr=subprocess.STDOUT)

From the docs:

args is required for all calls and should be a string, or a sequence of program arguments. Providing a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names). If passing a single string, either shell must be True (see below) or else the string must simply name the program to be executed without specifying any arguments.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...