Shebang for compiled Python code

假装没事ソ 提交于 2019-12-04 15:02:42

Shebang works only for text scripts, not binary files. Nevertheless, you can use binfmt_misc to execute *.pyc files directly, as reported in this Python ML thread:

Linux, you can use binfmt_misc to make executables out of pyc code. Run:

import imp,sys,string
magic = string.join(["\\x%.2x" % ord(c) for c in imp.get_magic()],"") 
reg = ':pyc:M::%s::%s:' % (magic, sys.executable) 
open("/proc/sys/fs/binfmt_misc/register","wb").write(reg)

once on your Linux system (or, rather, at boot time), and all pyc files become executable (if the x bit is set).

In Debian, installing the binfmt-support package will do that for you.

(emphasis is mine, note that this will apply to all Debian derivatives, including Ubuntu. The same solution works in Fedora too).

No. But you can use other OS-specific mechanisms for invoking arbitrary executable files, e.g. binfmt_misc.

Here is an updated python 3 version of Stefano Sanfilippo's answer:

import imp,sys,string
magic = "".join(["\\x%.2x" % c for c in imp.get_magic()])
reg = ':pyc:M::%s::%s:' % (magic, sys.executable) 
open("/proc/sys/fs/binfmt_misc/register","w").write(reg)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!