简体   繁体   English

python 3 - 如何将命令行参数中的“\\”保存为原始字符串

[英]python 3 - how to keep “\” from command line argument as raw string

Code is very simple: 代码很简单:

import sys
for arg in sys.argv:
    print(arg)

When I run it using: 当我使用以下方式运行它:

myProgram.py \\

It prints: 它打印:

C:\myProgram.py
\\

Since "\\" is special, under the hood, python addes extra "\\"s so the inputed "\\\\" becomes "\\\\\\\\", and when it prints it becames to "\\\\" again. 由于“\\”是特殊的,在引擎盖下,python会额外添加“\\”,因此输入的“\\\\”变为“\\\\\\\\”,并且当它打印时它再次成为“\\\\”。 How can I stop this, or delete the extra "\\"s added by python? 我怎么能阻止这个,或删除python添加的额外“\\”? So when the inputed argument is "\\\\", it prints "\\"; 所以当输入的参数是“\\\\”时,它会打印“\\”; and when the inputed argument is "\\t", it prints a [tab]; 当输入参数为“\\ t”时,它会打印一个[tab]; "\\n" to print a new line; “\\ n”打印一个新行; etc? 等等?

My search leads me to try the "raw string", so I changed my code to 我的搜索引导我尝试“原始字符串”,所以我将代码更改为

import sys
for arg in sys.argv:
    arg.replace(r'\\',r'\')
    print(arg)

But it throws error saying 但它引发了错误的说法

SyntaxError: EOL while scanning string literal

Seems the "raw string" is not working here? 似乎“原始字符串”在这里不起作用?

UPDATE: Screenshot with slight change 更新:屏幕截图略有变化

程序

产量

You want to evaluate argument as string, so you can use eval 您希望将参数计算为字符串,因此您可以使用eval

import sys
for arg in sys.argv:
    print(eval('"' + arg.replace('"', '\\"') + '"'))

WARNING: you should not use this approach in production, because Eval really is dangerous 警告:您不应该在生产中使用此方法,因为Eval确实很危险

我认为这个问题在本FAQ中有解释

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

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