如何使用包含其他参数的 argparse 解析参数
How to parse argument with argparse which contains other arguments
我正在使用 argparse 编写一个脚本,它应该接受用户输入。最后一个参数是 --args,对于这个参数,我想接受一串参数,然后将其传递给在我的脚本中调用的 bash 脚本。
这是一个真正简化的版本:
在Python (myscript.py):
import argparse
import subprocess
parser = argparse.ArgumentParser()
parser.add_argument("--name", type=str, help=description, default="")
parser.add_argument("--args", type=str, nargs='+', help=description, default="")
args = parser.parse_args()
subprocess.call("myotherscript.sh {}".format(args.script, args.args))
在Bash中:
python myscript.py --name myname --args --arguments for --the inner --script here
到目前为止,我已经尝试转义 Bash 中的 --
(例如 \--the inner
等),但我可以在 Python 中替换它们(" ".join([s.replace("\", "") for s in args.args])
), 但这不是很优雅。
我想知道是否有更好的方法用 argparse 来处理这个问题。
argparse
有可能only partially parse arguments。只要此脚本的参数与要传递的参数之间没有重叠,这就有效*。
import argparse
import subprocess
parser = argparse.ArgumentParser()
parser.add_argument("--name", help=description, default="") # default type is already str
args, other_args = parser.parse_known_args()
subprocess.call("myotherscript.sh {}".format(" ".join(other_args)))
您还可以通过使用 list
添加来避免 join
ing:
subprocess.call(["myotherscript.sh"] + other_args))
*如文档中所述:
Warning
Prefix matching rules apply to parse_known_args()
. The parser may
consume an option even if it’s just a prefix of one of its known
options, instead of leaving it in the remaining arguments list.
我正在使用 argparse 编写一个脚本,它应该接受用户输入。最后一个参数是 --args,对于这个参数,我想接受一串参数,然后将其传递给在我的脚本中调用的 bash 脚本。
这是一个真正简化的版本:
在Python (myscript.py):
import argparse
import subprocess
parser = argparse.ArgumentParser()
parser.add_argument("--name", type=str, help=description, default="")
parser.add_argument("--args", type=str, nargs='+', help=description, default="")
args = parser.parse_args()
subprocess.call("myotherscript.sh {}".format(args.script, args.args))
在Bash中:
python myscript.py --name myname --args --arguments for --the inner --script here
到目前为止,我已经尝试转义 Bash 中的 --
(例如 \--the inner
等),但我可以在 Python 中替换它们(" ".join([s.replace("\", "") for s in args.args])
), 但这不是很优雅。
我想知道是否有更好的方法用 argparse 来处理这个问题。
argparse
有可能only partially parse arguments。只要此脚本的参数与要传递的参数之间没有重叠,这就有效*。
import argparse
import subprocess
parser = argparse.ArgumentParser()
parser.add_argument("--name", help=description, default="") # default type is already str
args, other_args = parser.parse_known_args()
subprocess.call("myotherscript.sh {}".format(" ".join(other_args)))
您还可以通过使用 list
添加来避免 join
ing:
subprocess.call(["myotherscript.sh"] + other_args))
*如文档中所述:
Warning
Prefix matching rules apply to
parse_known_args()
. The parser may consume an option even if it’s just a prefix of one of its known options, instead of leaving it in the remaining arguments list.