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.

Community
  • 1
  • 1
Windsooon
  • 6,864
  • 4
  • 31
  • 50
  • 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. – O.rka Aug 17 '16 at 03:54
  • 1
    Possible duplicate of [importing a python script from another script and running it with arguments](http://stackoverflow.com/questions/28440441/importing-a-python-script-from-another-script-and-running-it-with-arguments) – Karin Aug 17 '16 at 03: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. – tdelaney Aug 17 '16 at 04: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. – tdelaney Aug 17 '16 at 04:27

1 Answers1

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)
Windsooon
  • 6,864
  • 4
  • 31
  • 50