使 python 文件在 Ubuntu 中可执行
在 Windows 中,要执行我的代码之一,我所要做的就是双击该文件。然而,我似乎不知道如何在 Ubuntu 中完成类似的任务。
In windows to make one of my codes execute all I have to do is double click on the file. However, I can't seem to figure out how to do a similar task in Ubuntu.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
确保将
#!/usr/bin/env python
作为脚本的第一行,然后在 shell 中执行以下操作:Make sure you have
#!/usr/bin/env python
as the first line of your script, then in your shell do:.pyw 文件只是已重命名的 .py 文件,以便 Windows 文件关联将使用无控制台的 Python 解释器而不是常规解释器启动它们。
要让 run-on-doubleclick 在 Ubuntu 上运行,首先,您需要确保内核将脚本视为可执行文件并知道如何处理它。为此:
chmod +xwhatever.pyw
)#!/ usr/bin/env python
(参见 wikipedia 了解更多信息)\n
) 行结尾而不是 DOS/Windows 风格的 CRLF (\r\n
) 行结尾保存的。 (内核期望第 2 步使用 Unix 风格的行结尾,如果您忘记了,它会将 CR (\r
) 字符视为路径的一部分并出错)您可以测试您是否已通过在终端窗口中运行脚本来正确完成这些步骤。 (
cd
到其所在目录并运行./your_script.pyw
)如果有效,Nautilus 应该会自动显示“编辑还是运行?”双击时出现对话框。然而,我已经有一段时间没有使用 GNOME 了,所以我不能确定。
如果没有,请尝试将文件重命名为
.py
。 (我记得 Nautilus 有一个“扩展名匹配标头?”安全检查,它可能不知道 .pyw 是 .py 的有效同义词).pyw files are just .py files that have been renamed so that Windows file associations will launch them with the console-free Python interpreter instead of the regular one.
To get run-on-doubleclick working on Ubuntu, first, you need to make sure the kernel sees the script as executable and knows what to do with it. To do that:
chmod +x whatever.pyw
)#!/usr/bin/env python
(See wikipedia for more info)\n
) line-endings rather than DOS/Windows-style CRLF (\r\n
) line-endings. (The kernel expects Unix-style line endings for step 2 and, if you forget, it sees the CR (\r
) character as part of the path and errors out)You can test whether you've completed these steps properly by running your script in a terminal window. (
cd
to the directory it's in and run./your_script.pyw
)If it works, then Nautilus should just automatically display an "Edit or run?" dialog when you double-click. However, it's been a while since I've used GNOME, so I can't be sure.
If it doesn't, try renaming the file to
.py
. (I remember Nautilus having a "Extension matches header?" safety check which may not be aware that .pyw is a valid synonym for .py)您必须使用 chmod 设置文件的权限才能使其可执行。有关详细信息,请参阅 chmod 的 手册页。
You have to set the permission for the file for it to be executable using
chmod
. See the manpages for chmod for details.