0

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?

2
  • Why do you want to call a Python function using subprocess instead of importing it??? Commented May 2, 2016 at 14:19
  • @PM2Ring I'm just learning to use subprocess, I now it's better to import the function, I was just curious. Commented May 2, 2016 at 14:21

2 Answers 2

2

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

Comments

2

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)

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.