简体   繁体   English

Python:编译成Unix命令行应用程序

[英]Python: compile into an Unix commandline app

I am not sure if I searched for the wrong terms, but I could not find much on this subject. 我不确定我是否搜索了错误的条款,但我在这个问题上找不到多少。 I am on osx and I'd like to compile a commandline python script into a small commandline app, that I can put into usr/local/bin so I can call it from anywhere. 我在osx上,我想将一个命令行python脚本编译成一个小命令行应用程序,我可以放入usr / local / bin,这样我就可以从任何地方调用它。 Is there a straighforward way to do that? 有没有直接的方法来做到这一点?

Thanks 谢谢

The simplest way to do this is to rename your file from filename.py to filename and add this line to the top of the file. 最简单的方法是将文件从filename.py重命名为filename ,并将此行添加到filename的顶部。

#!/usr/bin/env python

You may also need to set the executable bit on the file, which may be set using chmod +x on the command line. 您可能还需要在文件上设置可执行位,可以在命令行上使用chmod +x进行设置。

On Unix it works usually in the following way: 在Unix上,它通常以下列方式工作:

  1. Put #!/usr/bin/env python in the first line of your .py script. #!/usr/bin/env python放在.py脚本的第一行。
  2. Add execution permissions to the file (using chmod ). 向文件添加执行权限(使用chmod )。
  3. Execute the script from command line, eg. 从命令行执行脚本,例如。 by providing ./my_script.py when in the same directory. 通过在同一目录中提供./my_script.py

What else do you need? 你还需要什么?

A Python script is already a "command line app" that you can put anywhere. Python脚本已经是一个可以放在任何地方的“命令行应用程序”。

Just set the first line of your script to be a proper shebang pointing to your Python interpreter For example: 只需将脚本的第一行设置为指向Python解释器的正确shebang例如:

#! /usr/bin/python

(Or wherever OS X puts its Python interpreter), set your script with the executble attributes, and put it on your bin folder (或者OS X放置Python解释器的地方),使用executable属性设置脚本,并将其放在bin文件夹中

(it does not need to end in ".py" either) (它不需要以“.py”结尾)

you can write 你可以写

#!/usr/bin/python 

in the very beginning of your script or write shell script that will lauch your script like 在你的脚本的最开始或编写shell脚本,这将使你的脚本像

#!/bin/sh
python path_to_your_script/your_script.py

As almost everybody said, you can turn your script executable by adding the following line at the beginning of the script: 几乎每个人都说,你可以通过在脚本开头添加以下行来使脚本可执行:

#!/usr/bin/env python

and setting it to be executable: 并将其设置为可执行:

chmod +x script.py

Another alternative, is to convert your script into a native executable . 另一种方法是将脚本转换为本机可执行文件 For that, you may use Freeze or py2exe , depending on your target platform. 为此,您可以使用Freezepy2exe ,具体取决于您的目标平台。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM