1

Here are two scripts. First one called first_py:

  #!/usr/bin/env python  
    import sys   

    print sys.argv[0] # prints python_script.py    
    print sys.argv[1] # prints var1
    print "first one"

Here's the second one called sec_py:

#!/usr/bin/env python

import sys

print sys.argv[0] # prints sec_script.py
print sys.argv[1] # prints var1

print "second one"

x=5
myVars = {'x':x}
exec(open('first_py').read(), myVars)

As you can see I'm trying to pass the number '5' as a parameter from the second script to the first script while calling it. It's not working.

How can I fix the second script so it calls first_py and passes the value of 'x' to it so the value 5 is printed out?

Carbon
  • 313
  • 3
  • 11
  • 4
    Why don't you encapsulate the actual functionality into a function, and then just import and call it? – jonrsharpe Oct 29 '18 at 19:14
  • Possible duplicate of [Run a python script from another python script, passing in args](https://stackoverflow.com/questions/3781851/run-a-python-script-from-another-python-script-passing-in-args) – Tsyvarev Oct 29 '18 at 21:54

1 Answers1

0

Try:

#!/usr/bin/env python

import sys
import subprocess, shlex
print sys.argv[0] # prints sec_script.py
print sys.argv[1] # prints var1

print "second one"

x=5
myVars = {'x':x}
print subprocess.check_output(shlex.split('first_py {0}'.format(myVars['x'])))

There are many ways to do what you're trying to do - we should note particularly putting the print statement in a function (say, print_value()) in first_py, importing first_py, and then using first_py.print_value(myVars['x']). I think, however, that the subprocess solution is the closest one to the one you have already drafted.

PS - I would save my scripts as, e.g., first.py, rather than first_py.

Mark C.
  • 1,773
  • 2
  • 16
  • 26
  • Tried it and got the following error: $ ./sec_py.py TOM ./sec_py.py TOM second one Traceback (most recent call last): File "./sec_py.py", line 15, in print subprocess.check_output(shlex.split('first_py {0}'.format(myVars['x']))) NameError: name 'subprocess' is not defined – Carbon Oct 29 '18 at 19:58
  • I think you probably forgot `import subprocess, shlex` at the top (line #4) – Mark C. Oct 29 '18 at 21:02
  • But - seriously - use `import first_py; first_py.print_value(...)` way of doing it - it's a lot cleaner and better – Mark C. Oct 29 '18 at 21:03
  • Should I be including a path name to first_py because it's not recognizing the file. I'm getting. $ ./sec_py.py TOM File "./sec_py.py", line 4 import first_py,first_py.print_value(myVars['x']) ^ SyntaxError: invalid syntax – Carbon Oct 29 '18 at 21:28
  • Split `import first_py` and `first_py.print_value(...)` into separate lines! – Mark C. Oct 29 '18 at 21:31