Reputation: 2491
What is the proper way to pass values of string variables to Popen function in Python? I tried the below piece of code
var1 = 'hello'
var2 = 'universe'
p=Popen('/usr/bin/python /apps/sample.py ' + '"' + str(eval('var1')) + ' ' + '"' + str(eval('var2')), shell=True)
and in sample.py, below is the code
print sys.argv[1]
print '\n'
print sys.argv[2]
but it prints the below output
hello universe
none
so its considering both var1 and var2 as one argument. Is this the right approach of passing values of string variables as arguments?
Upvotes: 0
Views: 2820
Reputation: 2555
var1 = 'hello'
var2 = 'universe'
p=Popen("/usr/bin/python /apps/sample.py %s %s"%(str(eval('var1')), str(eval('var2'))), shell=True)
Passing format specifier is nice way to do it.
Upvotes: 0
Reputation: 59674
This should work:
p = Popen('/usr/bin/python /apps/sample.py {} {}'.format(var1, var2), shell=True)
Learn about string formatting .
Second, passing arguments to scripts has its quirks: http://docs.python.org/2/library/subprocess.html#subprocess.Popen
This works for me:
test.py:
#!/usr/bin/env python
import sys
print sys.argv[1]
print '\n'
print sys.argv[2]
Then:
chmod +x test.py
Then:
Python 2.7.4 (default, Jul 5 2013, 08:21:57)
>>> from subprocess import Popen
>>> p = Popen('./test.py {} {}'.format('hello', 'universe'), shell=True)
>>> hello
universe
Upvotes: 1