简体   繁体   English

如何导入使用argparse的模块

[英]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 我得到了模块调用foo.py,使用argparse来处理变量,需要一些变量,-a和一个元素

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: 这很好用,现在我得到一个元素列表,我尝试使用foo.py来运行所有这些。所以我创建了一个这样的脚本:

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

another option will be use execfile() 另一个选项是使用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? 我按照这里argparse模块如何添加没有任何参数的选项? , 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? 按照从另一个脚本导入python脚本并使用参数运行它 ,现在我可以很好地运行脚本,但是比向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. 或者我必须在main()完成后首先添加元素,而不是从sys.args中一遍又一遍地删除它。

Thanks to @Karin,This works great. 感谢@ Karin,这很棒。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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