Home > Backend Development > Python Tutorial > How to Properly Pass Variables to `subprocess.Popen()` without Shell Execution?

How to Properly Pass Variables to `subprocess.Popen()` without Shell Execution?

Barbara Streisand
Release: 2024-11-28 06:41:10
Original
362 people have browsed it

How to Properly Pass Variables to `subprocess.Popen()` without Shell Execution?

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']
Copy after login

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
)
Copy after login

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()
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template