如何从第二个脚本中执行包含argparse的脚本 [英] How to execute a script that has argparse from within a second script
问题描述
我有一个名为 test1.py
的简单脚本.
I have this simple script named test1.py
.
#!/usr/bin/env python
from argparse import ArgumentParser
def cmdlineparse():
parser = ArgumentParser()
parser.add_argument("-tid", dest="CHEMBL_TARGET_ID", required=True, type=str)
parser.add_argument("-molfile", dest="XTEST_MOLFILE", required=False, type=str)
args=parser.parse_args()
return args
if __name__ == '__main__':
args = cmdlineparse()
print("The given CHEMBL_TARGET_ID is %s" % args.CHEMBL_TARGET_ID)
print("The given XTEST_MOLFILE is %s" % args.XTEST_MOLFILE)
通常,我像这样执行 ./test1.py -tid CHEMBL8868 -molfile blends.sdf
.
我想做的是在名为 test2.py
的第二个脚本中多次执行它.最简单的解决方案是使用 subprocess.call
或类似方法来调用它.
What I want to do is to execute it multiple times from within a second script named test2.py
. The simplest solution would be to call it using subprocess.call
or something equivalent.
subprocess.call("./test1.py -tid CHEMBL8868 -molfile ligands.sdf".split(), shell=True, executable='/bin/bash')
但是,我想以一种更优雅的方式做到这一点,即将其作为模块导入并将值传递给 argparse
.有人可以告诉我该怎么做吗?
However, I would like to do it in a more elegant way, namely by importing it as a module and passing values to argparse
. Could someone please show me how to do this?
推荐答案
您需要稍微重构脚本:让 cmdlineparse
提取要解析的参数列表,并定义一个函数<代码>主要完成实际工作,而不是由<代码> __ main __ 保护的裸露块.
You'll need to refactor your script a bit: let cmdlineparse
take an list of arguments to parse, and define a function main
that does the actual work instead of a bare block guarded by __main__
.
#!/usr/bin/env python
from argparse import ArgumentParser
def cmdlineparse(args):
parser = ArgumentParser()
parser.add_argument("-tid", dest="CHEMBL_TARGET_ID", required=True, type=str)
parser.add_argument("-molfile", dest="XTEST_MOLFILE", required=False, type=str)
args=parser.parse_args(args)
return args
def main(args=None):
args = cmdlineparse(args)
print("The given CHEMBL_TARGET_ID is %s" % args.CHEMBL_TARGET_ID)
print("The given XTEST_MOLFILE is %s" % args.XTEST_MOLFILE)
if __name__ == '__main__':
main()
没有参数, main
将解析当前的命令行参数,因为 None
的值(最终)传递给了 parser.parse_args()
会使它解析 sys.argv [1:]
.
Without an argument, main
will parse the current command-line arguments, since a value of None
passed (eventually) to parser.parse_args()
will cause it to parse sys.argv[1:]
.
现在,您可以根据需要多次导入 test1
并显式调用 main
:
Now you can import test1
and call main
explicitly as often as you like:
import test1
test1.main(["-tid", "CHEMBL8868", "-molfile", "ligands.sdf"])
test1.main(["-tid", "CHEMBL8293", "-molfile", "stuff.sdf"])
# etc
这篇关于如何从第二个脚本中执行包含argparse的脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!