为什么要打包
- 可以在任意位置运行模块和包
- 不用输入python xxx.py,输入软件名称就可以直接运行
怎么打包
参考:Setuptools Integration — Click Documentation (7.x)
- 准备工作
mkdir hello & cd hellotouch setup.py hello.py
- setup.py内容 ```python from setuptools import setup
setup( name=’hello’, version=’0.1’, py_modules=[‘hello’], install_requires=[ ‘Click’, ], entry_points=’’’ [console_scripts] hello=hello:cli ‘’’, )
3. hello.py内容```pythonimport click@click.command()@click.option('-s', '--string', default='World',help="This is the thing that is greeted")@click.option('-n', '--number', default=1, help="This is the number of times to greet")@click.argument('output', type=click.File('w'), default='-',required=False)def cli(string,number,output):"""This scripts greets you."""for x in range(number):click.echo(f'Hello {string}', file=output)
- 然后运行下面这段代码,以把该脚本添加到环境
pip install --editable .
现在直接输入hello就可以运行了 ```shell $ hello —help Usage: hello [OPTIONS] [OUTPUT]
This scripts greets you.
Options: -s, —string TEXT This is the thing that is greeted -n, —number INTEGER This is the number of times to greet —help Show this message and exit.
$ hello —string “Achuan” —number 3 ./output.txt
<a name="eca0d553"></a>## 打包pygit尝试用python实现git操作setup.py内容```pythonfrom setuptools import setupsetup(name='pygit',version='0.1',py_modules=['pygit'],install_requires=['Click',],entry_points='''[console_scripts]pygit=pygit:cli''',)
pygit.py内容
import osimport clickfrom git.cmd import Gitimport datetimegit = Git(os.getcwd())@click.group()def cli():"""git 命令行"""pass@cli.command()def lazy():"""直接提交 add . commit Today"""# git addcmd = ['git', 'add','.']output = git.execute(cmd)# git commitmsg = ":memo:"+str(datetime.date.today())cmd = ['git', 'commit', '-m', msg]output = git.execute(cmd)# git pushcmd = ['git', 'push']output = git.execute(cmd)click.secho('done',fg='green')@cli.command()def status():"""处理 status 命令"""cmd = ['git', 'status']output = git.execute(cmd)click.echo(output)@cli.command()@click.argument('pathspecs', nargs=-1, metavar='[PATHSPEC]...')def add(pathspecs):"""处理 add 命令"""cmd = ['git', 'add'] + list(pathspecs)output = git.execute(cmd)click.echo(output)@cli.command()@click.option('-m', 'msg')def commit(msg):"""处理 -m <msg> 命令"""cmd = ['git', 'commit', '-m', msg]output = git.execute(cmd)click.echo(output)@cli.command()def push():"""处理 push 命令"""cmd = ['git', 'push']output = git.execute(cmd)click.echo(output)if __name__ == '__main__':cli()
之后就能pygit lazy快速提交当日代码了
$ pygit --helpUsage: pygit [OPTIONS] COMMAND [ARGS]...git 命令行Options:--help Show this message and exit.Commands:add 处理 add 命令commit 处理 -m <msg> 命令lazy 直接提交 add .push 处理 push 命令status 处理 status 命令$pygit lazy
