Why does passing variables to subprocess.Popen not work despite passing a list of arguments?
Drop shell=True
. The arguments to Popen()
are treated differently on Unix if shell=True
:
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 passing shell=True
for commands with external input is a security hazard, as described by a warning in the docs.
Using a variable in a subprocess.Popen command
You need shell=True
because otherwise it'll look for an executable with that name. shell=True
tells the method to use the shell to execute the command so >
and friends become what you originally intended them to be (redirection).
The following code you posted:
from subprocess import Popen, PIPE, STDOUT
files = raw_input('File Name: ')
p = subprocess.Popen(['hexdump files > hexdump.dat' ], stdout=PIPE, stderr=STDOUT)
out,err = p.communicate(input=files)
will not work because you're just passing files
to hexdump
, and if a file with the name files
doesn't exist you'll get an error (and if it does exist, it's still probably not what you wanted.)
What you want is to build the string you're executing:
file = "input.dat"
p = subprocess.Popen("hexdump " + file + " > hexdump.dat", shell=True)
Pass variable to subprocess
Something like
with open('iplist', 'r', encoding="utf-8") as ip_file:
for ip in ip_file:
cmd = ['./mmdbinspect', '--db', '/usr/local/var/GeoIP/GeoLite2-City.mmdb', ip.strip()]
result = subprocess.run(cmd, stdout=subprocess.PIPE)
print(result.stdout)
passing $_POST variable with subprocess.Popen
You should use popen
in Python and $argv[]
in PHP
Python Script
import os
value1 = 'test'
value2 = 'test2'
cmd = rf'php /mypath/myphp.php {value1} {value2}'
os.popen(cmd)
PHP Script
<?php
var_dump($argv); //['myphp.php', 'test', 'test2']
echo "Value1: ".$argv[1];
echo "Value2: ".$argv[2];
?>
Related Topics
On Linux Suse or Redhat, How to Load Python 2.7
Python's Equivalent for R's Dput() Function
Set the Hardware Clock in Python
Why Not Just Use 'Shell=True' in Subprocess.Popen in Python
Install Tkinter and Python Locally
How to Call Wine Dll from Python on Linux
Anaconda Python Not Available from Sudo
What Does -≫ Mean in Python Function Definitions
Difference Between Pip and Conda
Standalone Python Applications in Linux
How to Setup Environment Variable R_User to Use Rpy2 in Python
Gae " No Attribute 'Httpshandler' " Dev_Appserver.Py
How to Pass a Keystroke (Alt+Tab) Using Popen.Communicate (On Linux)