Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import the module which using argparse

Tags:

python

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.

like image 790
Windsooon Avatar asked May 05 '26 08:05

Windsooon


1 Answers

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)
like image 80
Windsooon Avatar answered May 09 '26 02:05

Windsooon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!