4

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?

1

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

Comments

3

in case of complex commands , you can use shlex to pass the commands as a list to Check_Output or any other subprocess classes

from the document

shlex.split() can be useful when determining the correct tokenization for args, especially in complex cases:

https://docs.python.org/3.6/library/subprocess.html#subprocess.check_output

coming to above example

import shlex
inp="md5 Downloads/test.txt"
command=shlex.split(inp)
subprocess.check_output(command, stderr=subprocess.STDOUT)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.