编译python .py文件而不执行

有没有办法从命令行编译Python .py文件而不执行它?

我正在处理一个应用程序,它的Python扩展存储在一个非标准的path中,并且有限的权限,我想在安装过程中编译这些文件。 我不需要Distutils的开销。

py_compile模块提供了从源文件生成字节码文件的function,以及当模块源文件作为脚本被调用时使用的另一个function。

python -m py_compile fileA.py fileB.py fileC.py 

是的,有模块编译:

http://docs.python.org/library/compileall.html#module-compileall

下面是一个编译目录中的所有.py文件的例子(但不包括子目录)

 python -m compileall -l myDirectory 

事实上,如果你在Linux上,你的PATH中可能已经有了一个/usr/bin/py_compilefiles命令。 它包装了其他人提到的py_compile模块。 如果你不在Linux上,这里是脚本代码 。

$ python -c "import py_compile; py_compile.compile('yourfile.py')"

要么

$ python -c "import py_compile; py_compile.compileall('dir')"

我会这样说,所以你可以编译它到你select的位置:

 import py_compile py_compile(filename+".py",wantedlocation+wantedname+".pyc") 

正如我现在在github.com/lolexorg/Lolex-Tools上的Python项目中所做的那样

除了selectpyc的输出位置(通过@Jensen Taylor的答案 ),如果不希望将py文件的绝对path写入pyc中,还可以指定一个用于回溯的源文件名:

python -c "import py_compile; py_compile.compile('src.py', 'dest.pyc', 'whatever_you_like')"

尽pipe“compileall -d destdir”也可以做到这一点,但是它有时会限制你的工作目录。 例如,如果你想在pyc中的源文件名是“./src.py”,你必须将工作目录移动到src.py文件夹中,这在某些情况下是不可取的,然后运行“python -m compileall -d ./“。