[英]How to execute a script that has argparse from within a second script
I have this simple script named test1.py
. 我有一个名为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)
Normally, I execute it like this ./test1.py -tid CHEMBL8868 -molfile ligands.sdf
. 通常,我像这样执行它./test1.py -tid CHEMBL8868 -molfile ligands.sdf
。
What I want to do is to execute it multiple times from within a second script named test2.py
. 我想要做的是从名为test2.py
的第二个脚本中多次执行它。 The simplest solution would be to call it using subprocess.call
or something equivalent. 最简单的解决方案是使用subprocess.call
或类似的方法来调用它。
subprocess.call("./test1.py -tid CHEMBL8868 -molfile ligands.sdf".split(), shell=True, executable='/bin/bash')
However, I would like to do it in a more elegant way, namely by importing it as a module and passing values to argparse
. 但是,我想以一种更优雅的方式做到这一点,即将其作为模块导入并将值传递给argparse
。 Could someone please show me how to do this? 有人可以告诉我该怎么做吗?
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__
. 您需要稍微重构一下脚本:让cmdlineparse
获取要解析的参数列表,并定义一个执行实际工作的函数main
而不是__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()
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:]
. 如果没有参数, main
将解析当前的命令行参数,因为(最终)传递给parser.parse_args()
的None
值将导致其解析sys.argv[1:]
。
Now you can import test1
and call main
explicitly as often as you like: 现在您可以导入test1
并根据需要test1
显式调用main
:
import test1
test1.main(["-tid", "CHEMBL8868", "-molfile", "ligands.sdf"])
test1.main(["-tid", "CHEMBL8293", "-molfile", "stuff.sdf"])
# etc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.