When utilizing subprocess.Popen() to invoke another Python script, passing variables as arguments can encounter unexpected issues. Let's investigate why this may occur and how to resolve it.
The provided code demonstrates an attempt to execute the script mytool.py with arguments stored in variables. However, the shell=True parameter may be hindering the execution.
Solution:
To enable successful variable passing, omit the shell=True parameter. Under Unix environments, enabling shell=True modifies how Popen() interprets arguments, potentially resulting in undesired behavior.
Here's a modified code snippet that addresses this issue:
import sys from subprocess import Popen, PIPE # populate list of arguments args = ["mytool.py"] for opt, optname in zip("-a -x -p".split(), "address port pass".split()): args.extend([opt, str(servers[server][optname])]) args.extend("some additional command".split()) # run script p = Popen([sys.executable or 'python'] + args, stdout=PIPE) # use p.stdout here... p.stdout.close() p.wait()
Security Note:
Using shell=True for commands involving external input is a security hazard. As stated in the Python documentation, this practice is discouraged due to potential vulnerabilities.
The above is the detailed content of Why Does Variable Passing Fail in `subprocess.Popen()` and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!