Variable Passing Issues with Subprocess.Popen()
When attempting to pass arguments stored in variables to subprocess.Popen(), some users experience difficulties. This is particularly the case when dealing with arguments like the following:
servers[server]['address'] servers[server]['port'] servers[server]['pass']
Applying these variables directly to the Popen() command as shown below can lead to errors:
p = subprocess.Popen( ["python mytool.py -a ", servers[server]['address'], "-x", servers[server]['port'], "-p", servers[server]['pass'], "some additional command"], shell=True, stdout=subprocess.PIPE )
Solution: Disable Shell Execution
To resolve this issue, remove the shell=True argument from the Popen() call. This will prevent the arguments from being treated specially by the shell, allowing them to be passed as strings instead.
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()
Note that using shell=True for commands taking user input presents security risks. Always consider alternative methods for protecting user input from potential vulnerabilities.
The above is the detailed content of How to Properly Pass Variables to `subprocess.Popen()` without Shell Execution?. For more information, please follow other related articles on the PHP Chinese website!