Python scripts in /usr/bin

社会主义新天地 提交于 2021-02-17 15:16:41

问题


I'm writing a pretty basic application in python (it's only one file at the moment). My question is how do I get it so the python script is able to be run in /usr/bin without the .py extension?

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

htswap args

Thanks in advance!


回答1:


Simply strip off the .py extension by renaming the file. 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.

You also have to make your file executable, with the command

chmod a+x htswap

And dump it into /usr/local/bin. This is cleaner than /usr/bin, because the contents of that directory are usually managed by the operating system.




回答2:


The first line of the file should be

#!/usr/bin/env python

You should remove the .py extension, and make the file executable, using

chmod ugo+x htswap

EDIT: Thomas points out correctly that such scripts should be placed in /usr/local/bin rather than in /usr/bin. Please upvote his answer (at the expense of mine, perhaps. Seven upvotes (as we speak) for this kind of stuff is ridiculous)




回答3:


Shebang?

#!/usr/bin/env python

Put that at the beginning of your file and you're set




回答4:


add #!/usr/bin/env python to the very top of htswap.py and rename htswap.py to htswap then do a command: chmod +x htswap to make htswap executable.




回答5:


I see in the official Python tutorials, http://docs.python.org/tutorial/index.html, that

#! /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. 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!



来源:https://stackoverflow.com/questions/1168042/python-scripts-in-usr-bin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!