简体   繁体   English

/ usr / bin中的Python脚本

[英]Python scripts in /usr/bin

I'm writing a pretty basic application in python (it's only one file at the moment). 我正在python中编写一个非常基本的应用程序(目前它只是一个文件)。 My question is how do I get it so the python script is able to be run in /usr/bin without the .py extension? 我的问题是如何获取它以便python脚本能够在没有.py扩展名的/ usr / bin中运行?

For example, instead of running 例如,而不是运行

python htswap.py args

from the directory where it currently is, I want to be able to cd to any directory and do 从目前的目录,我希望能够cd到任何目录,并做

htswap args

Thanks in advance! 提前致谢!

Simply strip off the .py extension by renaming the file. 只需重命名文件即可剥离.py扩展名。 Then, you have to put the following line at the top of your file: 然后,您必须将以下行放在文件的顶部:

#!/usr/bin/env python

env is a little program that sets up the environment so that the right python interpreter is executed. env是一个设置环境的小程序,以便执行正确的python解释器。

You also have to make your file executable, with the command 您还必须使用该命令使文件可执行

chmod a+x htswap

And dump it into /usr/local/bin . 并将其转储到/usr/local/bin This is cleaner than /usr/bin , because the contents of that directory are usually managed by the operating system. 这比/usr/bin更干净,因为该目录的内容通常由操作系统管理。

The first line of the file should be 该文件的第一行应该是

#!/usr/bin/env python

You should remove the .py extension, and make the file executable, using 您应该删除.py扩展名,并使用该文件使文件可执行

chmod ugo+x htswap

EDIT: Thomas points out correctly that such scripts should be placed in /usr/local/bin rather than in /usr/bin . 编辑: Thomas正确地指出这些脚本应该放在/usr/local/bin而不是/usr/bin Please upvote his answer (at the expense of mine, perhaps. Seven upvotes (as we speak) for this kind of stuff is ridiculous) 请赞成他的回答(也许是以我的利益为代价。对于这种东西,七个赞成票(就我们说的话)是荒谬的)

Shebang? 家当?

#!/usr/bin/env python

Put that at the beginning of your file and you're set 把它放在你文件的开头就可以了

添加#!/usr/bin/env python到极顶htswap.py和重命名htswap.pyhtswap然后执行命令: chmod +x htswap使htswap可执行文件。

I see in the official Python tutorials, http://docs.python.org/tutorial/index.html , that 我在官方的Python教程http://docs.python.org/tutorial/index.html中看到了这一点

#! /usr/bin/env python

is used just as the answers above suggest. 就像上面提到的答案一样使用。 Note that you can also use the following 请注意,您还可以使用以下内容

#!/usr/bin/python

This is the style you'll see for in shell scripts, like bash scripts. 这是您在shell脚本中看到的样式,例如bash脚本。 For example 例如

#!/bin/bash

Seeing that the official tuts go with the first option that is probably your best bet. 看到官方的关键是第一个选项可能是你最好的选择。 Consistency in code is something to strive for! 代码的一致性是值得努力的!

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

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