Using subprocess.Popen to run a batch file in Wind

2019-08-22 08:11发布

问题:

Why can we not use Popen to run a batch file?

>>> p = Popen(["filename"], shell=True, stdout = PIPE) 

This is working well, but according to the documentation we should not use shell = True for "running a batch file or console-based executable".

Why can't we use shell = True when it runs a batch file? Why should it only be used for building in cmd?

回答1:

Calling subprocess.Popen() with the shell parameter set to True in production is a generally bad idea. One of the dangers include shell injection vulnerabilities, as quoted by the Python 3 docs:

17.5.2. Security Considerations

Unlike some other popen functions, this implementation will never implicitly call a system shell. This means that all characters, including shell metacharacters, can safely be passed to child processes. If the shell is invoked explicitly, via shell=True, it is the application’s responsibility to ensure that all whitespace and metacharacters are quoted appropriately to avoid shell injection vulnerabilities.

Source: https://docs.python.org/3.6/library/subprocess.html