将文件拖放到 Windows 中的 Python 脚本中 - 避免 Windows 在参数中使用反斜杠

发布于 2025-01-05 03:33:34 字数 425 浏览 5 评论 0原文

我知道 Windows 如何使用反斜杠作为文件名等,而 Unix 如何使用正向。但是,我从不在代码中创建的字符串中使用反斜杠。但是:

当 Windows 资源管理器将文件“拖放到”Python 脚本上时,它传递的字符串包含反斜杠。这些转换为 sys.argv 列表中字符串中的转义序列,然后我无法在之后更改它们(欢迎那里的建议)

有什么方法可以让 Windows 传递文字字符串或...任何其他我怎样才能解决这个问题?

我希望我的脚本是可删除的,但唯一阻止我的是 Windows 反斜杠。

编辑:

抱歉大家,错误实际上不是字符串的传递 - 正如下面有人指出的那样,但这仍然可以帮助其他人:

确保使用绝对路径名,因为当 Windows shell 不会在当前目录,就像在命令行中一样。当尝试写入非绝对的单部分路径名时,这会导致权限被拒绝错误。

I know all about how Windows uses backslashes for filenames, etc., and Unix uses forward. However, I never use backslashes with strings I create in my code. However:

When windows explorer "drops" a file onto a python script, the string it passes contains backslashes. These translate into escape sequences in the strings in the sys.argv list and then I have no way to change them after that (open to suggestions there)

Is there any way I can somehow make windows pass a literal string or ... any other way I can solve this problem?

I'd love my script to be droppable, but the only thing preventing me is windows backslashes.

EDIT:

Sorry everyone, the error was actually not the passing of the string - as someone has pointed out below, but this could still help someone else:

Make sure you use absolute path names because when the Windows shell will NOT run the script in the current directory as you would from a command line. This causes permission denied errors when attempting to write to single-part path-names that aren't absolute.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

吃素的狼 2025-01-12 03:33:34

无法重现。这:

import os, sys
print sys.argv
print map(os.path.exists, sys.argv)
raw_input()

给了我这个:

['D:\\workspaces\\generic\\SO_Python\\9266551.py', 'D:\\workspaces\\generic\\SO_Python\\9254991.py']
[True, True]

将第二个文件放到第一个文件上之后。 Python 2.7.2(在 Windows 上)。你能试试这段代码吗?

Cannot reproduce. This:

import os, sys
print sys.argv
print map(os.path.exists, sys.argv)
raw_input()

gives me this:

['D:\\workspaces\\generic\\SO_Python\\9266551.py', 'D:\\workspaces\\generic\\SO_Python\\9254991.py']
[True, True]

after dropping the second file onto the first one. Python 2.7.2 (on Windows). Can you try this code out?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文