gpt4 book ai didi

Python 将 CMD 调用添加到 ArgParse

转载 作者:太空宇宙 更新时间:2023-11-04 12:12:04 26 4
gpt4 key购买 nike

我正在尝试向我的 Python 代码中的帮助部分添加一个选项。当用户使用 -h 运行 cmd 调用时,他们将收到以下提示。

如果他们不知道可用的节目是什么,我希望他们选择选项 -sl,它将运行 cmd 并在同一终端中输出列表作为结果。由于我经验不足,cmd涉及awk,引号也被证明是一个问题。

Untouched命令行调用如下:工作信息--allshow | awk -F "[, ]+"'/jobs/{print $(NF-1)}'

showlist = "jobsinfo --allshow | awk -F " + "[, ]+" + "'/jobs/{print     $(NF-1)}'"

# Help section
parser = argparse.ArgumentParser(description="Check the render queue for a time period")
parser.add_argument("-l", "--location", default=site, help="The location you want to check. ""#Examples: london, denver, montreal...")
parser.add_argument("-p", "--project", default="New", help="The project you want to check. The Default is set to new. "
"#Examples: Please see SHOW list here: http://dnet.dneg.com/display/COMMS/SHOW+INFORMATION")
# parser.add_argument("-sl", "--showlist", action=showlist, help="List the Shows currently on Servers.")
parser.add_argument("-d", "--days", type=int, default=14, help="The number of days you wish to go back. The default is set to 14 days. "
"#Examples: -d 3, -d 9, -d 14")
args = parser.parse_args()

如有任何帮助,我们将不胜感激。

谢谢!

最佳答案

这里只是给你一些想法。因为我没有你的jobsinfo程序,所以我使用下面的命令来运行

ls -l | awk 'NR < 10 { print " quoting no problem " $NF }' 

请注意,确实不推荐这样做,但这样做很容易。参见 http://mywiki.wooledge.org/ParsingLs

无论如何,对于您给出的代码,我只需要进行一些更改。 showlist 选项变成了

parser.add_argument("-s", "--showlist",
action='store_const', const=True,
help="List the Shows currently on Servers.")

这意味着如果您使用 -s 选项 (./argparse_help.py -s),那么您可以执行以下操作:

args = parser.parse_args()

if args.showlist:
print "showlist is True"
else:
print "showlist is False"

参见 API referencetutorial如果需要,来自 Python.org。

要实际运行命令,您可能需要 subprocess模块。例如,我使用了 Python 的原始多行字符串(r"""三引号字符串""")来避免引用问题(当然除了 shell 的引用) :

import subprocess
test_run = r""" ls -l |
awk 'BEGIN {
print "'\'' quotes are like they would be in the shell '\''"
}
NR < 10 {
print $NF
}'

"""
subprocess.call(test_run, shell=True)

运行时,这给出

~$> ./argparse_help.py -s
' quotes are like they would be in the shell '
117984
anvil_group.sh
a.out
argparse_help.py
a.text
awk
bin
Library
confused_out

这主要可以在 Python 中完成,这样就不必使用 shell=True:

import subprocess
print "' quotes are like in python '"
for line in subprocess.check_output(['ls', '-l']).splitlines()[:9]:
print line.split()[-1]

和输出:

~$> ./argparse_help.py -s
' quotes are like in python '
117984
anvil_group.sh
a.out
argparse_help.py
a.text
awk
bin
Library
confused_out

希望可以让你再次出发。

关于Python 将 CMD 调用添加到 ArgParse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48571792/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com