如何从第二个脚本中执行具有 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 -molfileligands.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
执行实际工作,而不是由 __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屋!