2qdxy4rz...@potatochowder.com 在 2023年1月24日 星期二凌晨2:47:12 [UTC+8] 的信中寫道: > On 2023-01-22 at 18:19:13 -0800, > Jach Feng <jf...@ms4.hinet.net> wrote: > > > 1) Modify the sys.argv by inserting an item '--' before parsing it, ie. > > sys.argv.insert(1, '--') > > args = parser.parse_args() > Please don't do that. :-) > > In my mind, sys.argv belongs to Python, not the application. Instead, > pass a newly created argument list to parse_args: > > args = parser.parse_args(['--'] + sys.argv) > > This approach (adjusting the actual arguments) will work until your > program actually has options. > > 2) By adding an extra space character before the leading '-' sign, ie. > > e:\Works\Python>py infix2postfix.py " -4^2+5.3*abs(-2-1)/2" > > -4 2 ^ 5.3 -2 1 - abs * 2 / + > > > > But no idea how it works? and if it can survive in a newer argparse > > version?:-) > It works because argparse checks the first character of each argument, > and *doesn't* strip/trim whitespace. So "-x" looks like an option, and > " -x" looks an argument. More pathonic, but don't work. The '--' must be at index 1:-)
>>> parser.parse_args(['--', 'infix2postfix.py', '-4.3+5']) usage: [-h] infix : error: unrecognized arguments: -4.3+5 -- https://mail.python.org/mailman/listinfo/python-list