【发布时间】:2022-01-13 00:01:10
【问题描述】:
使用 Typer 的带有 python 的 CLI 应用程序通过 $ python main.py 执行(我的文件名是 main.py)。这是代码的简化版本:
import typer
app = typer.Typer()
@app.command()
def hello(name: str, age: int, display_age: bool = True):
print(f"hello {name}",style="bold")
if display_iq:
print(f"your age is {age}")
@app.command()
def goodby():
print("Goodby")
if __name__ == "__main__":
app()
要调用hello 方法,您可以使用例如$ python main.py hello Jonh 25。其中John 和25 是参数。
但是我想通过自定义命令调用 CLI,使用类似 $ csc hello Jonh 25 的东西。
有可能吗?如果是这样,我该怎么做?
更新
我找到了这段代码来设置 cli 应用程序:
from setuptools import find_packages, setup
setup(
name='main',
version='0.0.0',
packages=find_packages(),
install_requires=[
'typer'
],
entry_points='''
[console_scripts]
csc=main:main
'''
)
我已将此代码放入文件setup.py 并使用pip install -e . 执行
它会安装包,所以当我调用 pip list 时,我的 cli 会出现在已安装包的列表中:
main 0.0.0 c:\projects\cli.
还会创建一个名为main.egg-info 的文件夹,其中包含几个文本文件。但是它返回下一个错误:
ERROR: Command errored out with exit status 1:
command: 'c:\python39\python.exe' -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'c:\\projects\\cli\\setup.py'"'"'; __file__='"'"'c:\\projects\\cli\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' develop --no-deps
Complete output (16 lines):
running develop
running egg_info
creating main.egg-info
writing main.egg-info\PKG-INFO
writing dependency_links to main.egg-info\dependency_links.txt
writing entry points to main.egg-info\entry_points.txt
writing requirements to main.egg-info\requires.txt
writing top-level names to main.egg-info\top_level.txt
writing manifest file 'main.egg-info\SOURCES.txt'
reading manifest file 'main.egg-info\SOURCES.txt'
writing manifest file 'main.egg-info\SOURCES.txt'
running build_ext
Creating c:\python39\lib\site-packages\main.egg-link (link to .)
main 0.0.0 is already the active version in easy-install.pth
Installing csc-script.py script to c:\python39\Scripts
error: [Errno 13] Permission denied: 'c:\\python39\\Scripts\\csc-script.py'
----------------------------------------
ERROR: Command errored out with exit status 1: 'c:\python39\python.exe' -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'c:\\projects\\cli\\setup.py'"'"'; __file__='"'"'c:\\projects\\cli\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__)
else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' develop --no-deps Check the logs for full command output.
因此,csc 命令不起作用。我的 Python 版本是 3.9.6。
有什么线索吗?
【问题讨论】:
标签: python command-line-interface typer