0

I have a module which accepts arguments from the command line, let's call that module A.

I would like to execute A from another module - B, so that B will set A's arguments-

without executing A as a separate process.

Any way to do that?

1
  • No pretty way if A doesn't cooperate (e.g. by having a main(argv) function). I presume you can't change it to do that? Commented Dec 23, 2012 at 17:54

3 Answers 3

3

That depends on how module A takes it's arguments. If it only looks at sys.argv and has no __main__ test, then you could alter sys.argv:

sys.argv[1:] = ['arg1', 'arg2']

then import module A.

However, if you are writing A yourself, use a function, called from a __main__ test instead:

def main(*args):
    # main code for module

if __name__ == '__main__`:
    import sys
    main(*sys.argv[1:])

then you can import A and call main() directly:

import A
A.main('arg1', 'arg2')

Note that if module A is not your own, and it does have a __main__ test, but does all the work in that if __name__ == '__main__': suite, then you are sunk and have to reproduce that code.

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

1 Comment

@JoranBeasley: well, let's see if being the fastest counts for that much. :-P
2

Just define a main method in your script so that it can be run from both the command line and as a module:

def main(arg1, arg2):
    # All your code goes here

if __name__ == '__main__':
    main(*sys.argv[1:])

Then you can do either:

$ a.py x y

Or

>>> import a
>>> a.main('x', 'y')

Comments

0
import sys
sys.argv[1:] = ["My Arguments","other Args"] #dont replace [0] ...since it can let you know which script was actually executed ...

import A
A.run() #or whatever

I think will work ... not really recommended but ....

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.