3

I got the module call foo.py, use argparse to handle variables, requires some variables, -a and a element

python foo.py -a element

This works well, now I get a list of elements, I try to use foo.py to run all of them.So I create a script like this:

import foo
for i in range(len(element)):
# how to run foo and pass -a here?

another option will be use execfile()

execfile("foo.py") #should I set the -a as some global variable here?

I follow here argparse module How to add option without any argument?, I don't quite understand how to do this.

EDIT

Follow importing a python script from another script and running it with arguments, Now I can run the script well, But any better solution than add a list to sys.args? Or I have to add the element first, after the main() finish, than delete it from sys.args and over and over again.

4
  • Is this not what you want? p.add_argument('-f', '--foo', action='store_true') I'm confused on what you're asking. If you wan like a boolean thing then store_true is the way to go. Commented Aug 17, 2016 at 3:54
  • 1
    Possible duplicate of importing a python script from another script and running it with arguments Commented Aug 17, 2016 at 3:54
  • 4
    @karin - interesting link but will not work for scripts that use a if __name__ == "__main__": conditional because the imported module will have a different name. Commented Aug 17, 2016 at 4:03
  • Ideally a script intended to be used as a script and a module has some sort of main function that takes an argv-like parameter list. If so, just call that function with the parameters. Commented Aug 17, 2016 at 4:27

1 Answer 1

4

Thanks to @Karin,This works great.

import sys
sys.argv += ['-a','-H MYHOSTNAME' .... other options]
from pyrseas import dbtoyaml
dbtoyaml.main()

And this also work.

proc = subprocess.Popen(['python', 'foo.py',  '-a', 'bala'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
Sign up to request clarification or add additional context in comments.

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.