python - 我如何将python与bash中的py文件相关联

标签 python linux bash

一个常见的问题是“如何在不在命令行上显式调用 python 的情况下使 my python 脚本可执行?”,答案是 chmod +x 它和然后在脚本的开头添加 #!/usr/bin/env python

这不是我要问的问题。

我想做的是告诉 bash 或 python,或任何负责文件处理的东西,将所有设置了执行位的 .py 文件视为它们在开头有 shebang,无论它们实际上是否做。

我知道在 Windows 中可以做到这一点,显然在 Gnome 中,您可以在 GUI 中双击 .py 脚本的用例。我可以发誓我记得听说过从 shell 指定处理程序的等效方法。

为什么我想知道如何做到这一点(如果真的可行的话):

  • 并非每个系统都使用 shebang,我不想用它弄乱跨平台项目中的文件。
  • 如果我向不属于我的项目提交补丁,为了自己的方便而将与补丁无关的内容放入其中对我来说有点令人讨厌。

谢谢。

最佳答案

你是说binfmt_misc

binfmt_misc is a capability of the Linux kernel which allows arbitrary executable file formats to be recognized and passed to certain user space applications, such as emulators and virtual machines.

所以你想给它注册一个入口,所以每次你想执行一个.py文件时,内核都会把它传递给/usr/bin/python。

你可以通过尝试这样的事情来做到这一点

# load the binfmt_misc module
if [ ! -d /proc/sys/fs/binfmt_misc ]; then
  /sbin/modprobe binfmt_misc
fi
if [ ! -f /proc/sys/fs/binfmt_misc/register ]; then
  mount binfmt_misc -t binfmt_misc /proc/sys/fs/binfmt_misc
fi

echo ':Python:E::py::/usr/bin/python:' > /proc/sys/fs/binfmt_misc/register  

如果您使用的是基于 Debian 的发行版,则必须安装 binfmt-support .

你可以添加 :Python:E::py::/usr/bin/python:/etc/binfmt.d/python.conf 所以它是永久的重启后。

关于python - 我如何将python与bash中的py文件相关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37648213/

相关文章:

python - Keras 中的输入和输出维度错误

python - 找不到文件错误 : [Errno 2] No such file or directory (python error)

linux - bash脚本小写输入文件中的每个字符串并将结果输出到新文件

mysql - mysql输出的列宽

python - Tkinter 破坏 Toplevel 并产生另一个错误

python - 如何在 python-telegram-api 的 ConversationHandler 中管理当前状态

linux - 如何通过命令提示符检查 Linux 中的 BIOS 版本或名称?

linux - 在 JupyterHub 中创建的默认系统用户的密码

c - 为什么 Linux 在目录上使用 getdents() 而不是 read()?

linux - 如何安全地抑制命令输出?