2

Possible Duplicate:
Run a python script from another python script, passing in args

Suppose I have script2.py that returns a int value.

Is it possible to run only script.py on my shell and within script.py gets in some way the int value returned by script2.py according to parameters I passed to script.py?

Community
  • 1
  • 1
Matt
  • 53
  • 1
  • 1
  • 4

3 Answers3

4

Yes it's possible. That's what modules are used for :).

First you have to put the method that you use in script2.py into a function. I'll use the same example as the person above me has used (because it's a good example :p).

def myFunction(a, b):
    return a + b

Now on your script.py, you'll want to put:

import script2

at the top. This will only work if both files are in the same directory.

To use the function, you would type:

# Adding up two numbers
script2.myFunction(1, 2)

and that should return 3.

TerryA
  • 58,805
  • 11
  • 114
  • 143
0

Could execfile be what you're after? execfile('script2.py') will work as if you had copied and pasted the entire contents of script2.py into the console.

e.g. suppose script2.py has:

 def myFunction(a, b):
     return a + b

and then in script.py I could do:

 # reads in the function myFunction from script2.py
 execfile('script2.py')
 myFunction(1, 2)

If you want to execute script2.py with parameters passed in from script.py then I suggest that the contents of script2.py are encased in a function. That is, if your script2.py is:

a = 1
b = 2
result = a + b

I'd suggest you convert it into:

 def myFunction(a, b):
     return a + b

so that you can specify a and b from script.py.

mathematical.coffee
  • 55,977
  • 11
  • 154
  • 194
0

Try this:

import subprocess

x = 55

print "running bar.py..."
subprocess.call("python bar.py " + x)
ATOzTOA
  • 34,814
  • 22
  • 96
  • 117