一.argparse参数解析
直接上代码:
import argparse
options = {}
def parserDeal():
parser = argparse.ArgumentParser(description='Display User info by FiledepotPath and Rows')
parser.add_argument('-F',
metavar="<FilePath>",
action="store",
type=str,
dest="depotPath",
help='File depot Path(s)')
parser.add_argument('-R',
metavar="<Rows>",
action="store",
type=int,
dest="Rows",
help='code line Numbers,be used to Get UserInfo(s)')
global options
options = parser.parse_args()
https://www.cnblogs.com/happystudyeveryday/p/16590921.html
比较需要关注的点有
- 参数命名.可选参数有长短两个命名。eg:
group.add_argument("-d", "--down")
- 必选参数
required=True
- 参数默认值
default='hello'
- 参数类型
type=
argparse --- 命令行选项、参数和子命令解析器 — Python 3.10.2 文档
argparse库的作用及其用法详解_Merlin_CAE的博客-CSDN博客
其中还有一种解析方式
parser = argparse.ArgumentParser(description="pcg cook", conflict_handler='resolve', add_help=False)
parser.add_argument('-hq_pcgdata_dir', help="hqueue shared folder pcg data dir", default="none")
parser.add_argument('-report_name', help='name of report', default='')
parser.add_argument('-build_scene_info', help='switch to build scene info', default='false')
parser.add_argument('-clear_cook_cache', help='switch to clear cook cache', default='false')
# distributed partial gen
parser.add_argument('-partial_gen', help="for distributed partial generation, e.g. 2/5", default="")
# project args
parser.add_argument('-project', help='project path', default='none')
parser.add_argument('-cook_racing', help="cookracing profile name, e.g. -cook_racing=Default", default="None")
# parse args
known_args = parser.parse_known_args()
args = known_args[0]
if len(sys.argv) == 1 or args.help > 0:
parser.print_help()
sys.exit(0)
global run_args
run_args = known_args[1]
global root_dir
if args.hq_pcgdata_dir != "none":
root_dir = args.hq_pcgdata_dir
global svn_commit_msg
svn_commit_msg = args.svn_commit_msg
二. 利用getopt
模块来解析命令行参数
opts, args = getopt.getopt(argv, "-h", ["help", "OutputDir=", "Patch=", "ToClient=", "ToServer=", "AllToDS=", "Area="])
:这行代码调用 getopt.getopt()
方法来解析命令行参数。argv
是传递给脚本的命令行参数列表。
getopt.getopt()
方法会返回两个值:opts
和 args
。opts
是一个包含选项和对应值的元组列表,args
是一个包含不属于任何选项的参数列表。
例如,如果你的命令行参数是 --p4port=1234 --p4user=user --OutputDir=/path/to/dir file1 file2
,那么 opts
将包含 [("--p4port", "1234"), ("--p4user", "user"), ("--OutputDir", "/path/to/dir")]
,args
将包含 ["file1", "file2"]
。
try:
opts, args = getopt.getopt(argv, "-h", ["help", "p4port=", "p4user=", "p4pass=", "p4client=", "BranchTag=",
"BaseChangelist=", "ChangeLists=", "ShelveIDs=",
"AppVer=", "ResVer=", "OutputDir=", "Patch=",
"ToClient=", "ToServer=", "AllToDS=", "Area="])
except getopt.GetoptError as e:
print(e)
sys.exit(2)
for opt, arg in opts:
if opt in ('-h', '--help'):
sys.exit(2)
else:
print(opt, arg)
if opt in '--BranchTag':
global BranchTag
BranchTag = arg
elif opt in '--ResVer':
global ResVer
ResVer = arg.replace(' ', '')
elif opt in '--OutputDir':
global OutputDir
"h"
是一个短选项,表示脚本支持-h
选项。["help", "OutputDir=", "Patch=", "ToClient=", "ToServer=", "AllToDS=", "Area="]
是一个长选项列表,表示脚本支持的长选项。
这段代码的作用是解析命令行参数,并将选项和对应的值存储在 opts
中,将不属于任何选项的参数存储在 args
中,以便在后续的代码中使用。
三.直接字符串解析
for idx in range(1, len(sys.argv)):
param = sys.argv[idx]
if param == "-ForceSync":
bForceSync = True
elif param == "-DeleteWorkspace":
bDeleteWorkspace = True
elif param.startswith("-StreamAddress="):
p4StreamAddress = param[len("-StreamAddress="):]
tmpVars = p4StreamAddress.split('/')
streamName = tmpVars[len(tmpVars) - 1]
p4EnvVars["P4CLIENT"] = "%s[%s]%s" % (pipelineName, hostName, streamName)
elif param.startswith("-WorkspacePath="):
workspacePath = param[len("-WorkspacePath="):]
elif param.startswith("-ConfigCacheFolder="):
configCacheFolder = param[len("-ConfigCacheFolder="):]
elif param.startswith("-P4USER="):
p4EnvVars["P4USER"] = param[len("-P4USER="):]
elif param.startswith("-P4PORT="):
p4EnvVars["P4PORT"] = param[len("-P4PORT="):]
elif param.startswith("-P4PASS="):
p4Pass = param[len("-P4PASS="):]
elif param.startswith("-P4CLIENT="):
p4ClientCustom = param[len("-P4CLIENT="):]
elif param.startswith("-SyncVer="):
syncVer = param[len("-SyncVer="):]