如何在Python中创建可以与PIP一起安装的CLI? [英] How to create a CLI in Python that can be installed with PIP?
问题描述
正如标题所示,我正在尝试使python脚本可从命令行访问.我发现了 click 和
As the title suggests, I'm trying to make a python script accessible from the command line. I've found libraries like click and argv that make it easy to access arguments passed from the command line, but the user still has to run the script through Python.
代替
python /location/to/myscript.py
我希望能够做到
myscript
从任何目录
据我了解,我可以通过编辑PATH变量在计算机上实现此目的.但是,我希望能够简单地做到这一点:
From what I understand, I can achieve this on my computer by editing my PATH variables. However, I would like to be able to simply do:
pip install myscript
,然后从任何地方键入 myscript
来访问脚本.我会在 setup.py
中放入一些特殊代码吗?
and then access the script by typing myscript
from anywhere. Is there some special code I would put in the setup.py
?
推荐答案
您可以使用 setuptools
一个很好的 setup.py
的示例(例如,您的软件包需要使用pandas和numpy):
an example of a nice setup.py
(say your package requires pandas and numpy):
import setuptools
setuptools.setup(
name='myscript',
version='1.0',
scripts=['./scripts/myscript'],
author='Me',
description='This runs my script which is great.',
packages=['lib.myscript']
install_requires=[
'setuptools',
'pandas >= 0.22.0',
'numpy >= 1.16.0'
],
python_requires='>=3.5'
)
您的目录应如下设置:
[dkennetz package]$ ls
lib scripts setup.py
内部lib将是:
[dkennetz package]$ ls lib
myscript
在 myscript
里面的
应为:
[dkennetz package]$ ls lib/myscript
__main__.py
__init__.py
helper_module1.py
helper_module2.py
main将用于调用您的函数并执行您想做的任何事情.
main would be used to call your function and do whatever you want to do.
内部脚本为:
[dkennetz package]$ ls scripts
myscript
, myscript
的内容为:
#!/usr/bin/env bash
if [[ ! $@ ]]; then
python3 -m myscript -h
else
python3 -m myscript $@
fi
然后运行即可: python setup.py install
这将安装您的程序以及setup.py中包含在 install_requires = []
中的所有依赖项,并将 myscript
作为命令行模块安装:/p>
which will install your program and all of the dependencies you included in install_requires=[]
in your setup.py and install myscript
as a command-line module:
[dkennetz ~]$ myscript
这篇关于如何在Python中创建可以与PIP一起安装的CLI?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!