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?

0

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

Why would you use execfile to import a function rather than import?
maybe they have non-function objects that need to be called?
0

Try this:

import subprocess

x = 55

print "running bar.py..."
subprocess.call("python bar.py " + x)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.