简体   繁体   中英

How to import the module which using argparse

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM