Reputation: 10433
If I have a function in a file like this:
def foo():
print 'foo'
foo()
I can call this file from another one:
import subprocess
subprocess.call(['python', 'function.py'])
But can if the function needs arguments:
def foo(foo_var):
print foo_var
Can I still call the function using subprocess?
Upvotes: 0
Views: 1467
Reputation: 81684
Can I still call the function using subprocess?
Yeah.
First you will need to pass the arguments to the function:
from sys import argv
def foo(args):
print args
>> ['arg1', 'arg2'] # (based on the example below)
foo(argv[1:])
Then in your calling code:
import subprocess
subprocess.call(['python', 'function.py', 'arg1', 'arg2'])
Upvotes: 2
Reputation: 298532
Instead of using subprocess
, just modify function.py
to have it work nicely with imports:
def foo():
print 'foo'
if __name__ == '__main__':
foo()
Then you can just import foo
from the function
module:
from function import foo
if __name__ == '__main__':
foo(1)
Upvotes: 2