0

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?

1
  • str(eval('var1'))is the same as 'var1'. Commented Oct 21, 2013 at 8:27

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

and is there a way to return control from the called python script to the calling python script?
The control is returned to the called script when it terminates.
0
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.