求教 python 命令行工具编写问题

2014-06-21 22:46:18 +08:00
 liaa
用python写一个命令行脚本greet.py比如打印出"hello world".每次使用的时候都需要在终端敲下这个

> python greet.py
> "hello world"

请问如何将这个greet.py转变成下面这种直接调用的方式

> greet
> "hello world"

* 不需要输入python
* 不要定位到greet.py所在的文件夹中去执行
2834 次点击
所在节点    问与答
7 条回复
Cynic222
2014-06-21 22:49:12 +08:00
alias greet=python /yout_path/greet.py
liaa
2014-06-21 22:53:35 +08:00
@Cynic222 嗯,这对我来说够用了!

我希望把这个脚本打包给其他人用,但是不需要他们手动去做alias,应该怎么做才最好.
binux
2014-06-21 22:54:31 +08:00
#!/usr/bin/env python

然后将这个文件拷贝或者软连接到 /usr/local/bin/ 下,改名为 greet
tongle
2014-06-21 22:57:48 +08:00
在/user/bin下做个链接到greet.py就可以了
tongle
2014-06-21 23:03:16 +08:00
@tongle 手滑了,见笑
timonwong
2014-06-22 00:17:58 +08:00
The Hard Way (and cross platform, on windows, it will generated a launcher application named greet.exe):

# Requirements

* setuptools
* Define your main function, for example: def main()

setup.py:


from setuptools import setup

setup(
# other arguments here...
py_modules=['greet.py'],
entry_points={
'console_scripts': [
'greet = greet:main',
],
}
)
lm902
2014-06-22 09:27:43 +08:00
#添加 #!/usr/bin/env python 到文件开头
sudo cp greet.py /usr/bin/greet
sudo chmod +x /usr/bin/greet

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/118845

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX