[英]Sanitizing user input path names
Using Python 2.6 on Windows I have a function that needs to accept a path name as an arg. 在Windows上使用Python 2.6,我有一个需要接受路径名作为arg的函数。 I'm running into issues when certain specific paths are passed. 通过某些特定路径时,我遇到了问题。
C:\users\bob\something.png #this is handled no prob.
C:\users\bob\nothing.png #this generates a WindowsError
C:\users\bob\test.png #this also generates a WindowsError
What I'm gathering is that the \\n
in the "nothing" path is being interpreted as a new line, and the \\t
in the "test" path is being interpreted as a tab. 我正在收集的内容是,“ nothing”路径中的\\n
被解释为新行,而“ test”路径中的\\t
被解释为制表符。
If I print out the path names, that's what appears to be happening. 如果我打印出路径名,那似乎正在发生。
print os.path.abspath("C:\users\bob\nothing.png")
C:\users\bob
othing.png
Same for the 'test' path, except a tab instead of a new line. 与“测试”路径相同,但使用制表符代替换行符。
The only thing I've come up with so far is to do a check to see if \\n
or \\t
are in the path name, and then handle it accordingly, but there must assuredly be a better way. 到目前为止,我唯一想出的就是检查路径名中是否有\\n
或\\t
,然后进行相应的处理,但是肯定有更好的方法。
if '\n' in path_name:
#escape slash, move on
What would a better way be? 有什么更好的办法?
print os.path.abspath(r"C:\users\bob\nothing.png")
may be what your looking for ... 可能是您想要的...
although user input should automatically be escaping the slash ... 尽管用户输入应自动转义斜线...
>>> a = raw_input("Enter Path:")
Enter Path:C:\www\a\nothing.jpg
>>> a
'C:\\www\\a\\nothing.jpg'
as you can see from this example user input is indeed escaped 从该示例中可以看到,用户输入确实被转义了
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.