[英]Passing argument with a forward slash in python argparse
I am using argparse to get command line arguments like:我正在使用 argparse 获取命令行 arguments,例如:
parser = argparse.ArgumentParser()
parser.add_argument('execCmd' , type=str)
args = parser.parse_args()
print(args)
Now when I run it from command line like this:现在,当我像这样从命令行运行它时:
$python script.py "/bin/exec 10"
The result on the console is控制台上的结果是
Namespace(execCmd='C:/Program Files/usr/bin/exec 10')
It prepends the file path to the argument.它将文件路径添加到参数中。 The user may start the command with a '/' or they may not.
用户可以使用“/”开始命令,也可以不使用。 Is there a way to handle this in argeparse such that the command is passed as it is without the file directory if the user adds '/'?
有没有办法在 argeparse 中处理这个问题,如果用户添加“/”,则命令按原样传递而没有文件目录?
Anyways, argparse can take in functions for the type and you can do something like a check to see if the first character of what they pass in is a /
or not.无论如何, argparse 可以接受类型的函数,你可以做一些类似检查的事情,看看他们传入的第一个字符是否是
/
或不是。
So like:所以像:
def check_slash(string):
if string and len(string) > 0 and string[0] == '/':
return string
else:
return 'C:/Program Files/' + string
parser.add_argument('execCmd' , type=check_slash)
The issue is with bash as defined here: https://github.com/bmatzelle/gow/issues/196问题出在此处定义的 bash: https://github.com/bmatzelle/gow/issues/196
I was running this from git bash and therefore it was appending the gow path to the argument.我从 git bash 运行它,因此它将 gow 路径附加到参数中。 Passing the argument as
将参数传递为
$python script.py "//bin\exec 10"
works and so does leaving a space有效,留下空间也是如此
$python script.py " /bin/exec 10"
This is not an issue if same command is run in powershell.如果在 powershell 中运行相同的命令,这不是问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.