简体   繁体   English

将命令行参数传递给Python whos字符串包含元字符

[英]Passing a command line argument to Python whos string contains a metacharacter

I am attempting to pass in a string as input argument to a Python program, from the command line ie $python parser_prog.py <pos1> <pos2> --opt1 --opt2 and interpreting these using argparse. 我试图将一个字符串作为输入参数传递给Python程序,从命令行,即$python parser_prog.py <pos1> <pos2> --opt1 --opt2并使用argparse解释这些。 Of course if contains any metacharacters these are first interpreted by the shell, so it needs to be quoted. 当然,如果包含任何元字符,这些首先由shell解释,因此需要引用它。

This seems to work, strings are passed through literally, preserving the \\*?! 这似乎工作,字符串通过字面传递,保留\\ *?! characters: 特点:

$ python parser_prog.py 'str\1*?' 'str2!'

However, when I attempt to pass through a '-' (hyphen) character, I cannot seem to mask it. 但是,当我试图通过' - '(连字符)字符时,我似乎无法掩盖它。 It is interpreted as an invalid option. 它被解释为无效选项。

$ python parser_prog.py 'str\1*?' '-str2!'

I have tried single and double quotes, is there a way to make sure Python interprets this as a raw string? 我试过单引号和双引号,有没有办法确保Python将其解释为原始字符串? (I'm not in the interpreter yet, this is on the shell command line, so I can't use pythonic expressions such as r'str1' ) (我还没在解释器中,这是在shell命令行,所以我不能使用r'str1'表达式,如r'str1'

Thank you for any hints! 谢谢你的任何提示!

As you said yourself, Python only sees the strings after being processed by the shell. 正如您自己所说,Python仅在shell处理后才能看到字符串。 The command-line arguments '-f' and -f look identical to the called program, and there is no way to dsitinguish them. 命令行参数'-f'-f看起来与被调用的程序完全相同,并且没有办法对它们进行说明。 That said, I think that argparse supports a -- argument to denote the end of the options, and everything after this is treated as a positional argument. 也就是说,我认为argparse支持一个--参数来表示选项的结束,并且在此之后的所有内容都被视为位置参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM