编译Python代码的 Shebang

3

我曾经在Python脚本的顶部添加过shebang行,如下所示:

#!/usr/bin/python
...

我可以通过以下方式执行my.py文件:

chmod a+r my.py
./my.py

但是,在编译成字节码后,脚本只能由Python执行,并且shebang不再起作用。

python my.pyc

有没有办法让 shebang 对编译后的 Python 脚本起作用?
./my.pyc

2
你不应该执行.pyc文件,为什么要这样做? - Thomas Orozco
1
我们必须交付编译后的pyc文件而不是源代码作为我们产品的一部分。 - Takol
请记住,使用FOSS工具可以轻松从Python字节码中恢复完整的源代码(包括docstrings)。有一些DIY技术可以使反编译变得更加困难,但是对于Python来说并没有真正的混淆器。当然,这并不意味着您应该分发完整的源代码,但请记住,反转pyc几乎是微不足道的。 - Stefano Sanfilippo
2
嗨Stefano,感谢你的提醒。通常情况下,交付.pyc意味着“好的,我知道你可以反编译它,但请注意我不希望你这样做。” - Takol
3个回答

7

Shebang只针对文本脚本起作用,不适用于二进制文件。然而,你可以使用binfmt_misc直接执行*.pyc文件,正如这个Python ML线程所报告的:

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.

(强调是我的,注意这将适用于所有Debian衍生版,包括Ubuntu。相同的解决方案也适用于Fedora。)

你好Stefano。这个方法支持同一主机上许多Python版本(和.pyc),对吗?我可以在procfs中设置Python解释器及其选项吗? - Massimo

0

这是Stefano Sanfilippo答案的更新版本,使用Python 3编写:

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)

1
根据 https://docs.python.org/3/library/imp.html#imp.get_magic ,importlib.util.MAGIC_NUMBERimp 的新替代品。 - Marcin

0

不行。但是你可以使用其他特定于操作系统的机制来调用任意可执行文件,例如binfmt_misc


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接