将Python脚本转换为包时出错:<star.cli.CLI object at ...>

问题描述 投票:0回答:1

我在尝试将 Python 脚本转换为包时遇到问题。当作为 Python 文件执行或使用 PyInstaller 创建独立的可执行文件时,该脚本可以完美运行。但是,当我将其转换为包并运行它时,我在每个命令的末尾都会收到以下消息:

项目结构:

src/
    star/
        __init__.py
        __main__.py
         cli.py
         version.py
- setup.py

代码

cli.py

import os
import json
import argparse
from console import Console
from .version import __version__


console = Console()

class CLI:
    def __init__(self) -> None:
        self.config = {}

        # Command Line Argument
        self.parser = argparse.ArgumentParser(description="Star - Command Line Tool")
        self.parser.add_argument("script", metavar="script", nargs="?", default=None, help="Name of the script to run")
        self.parser.add_argument("-v", "--version", action="store_true", help="Display the version of Star")
        self.parser.add_argument("-l", "--list", action="store_true", help="List all available scripts", default=False)

        self.args = self.parser.parse_args()
        self.read_config_file()

        # Check for version flag
        if self.args.version:
            self.display_version()
        elif self.args.list or self.args.script is None:
            self.display_script_list()
        else:
            self.run_script(self.args.script)


    def read_config_file(self) -> None:
        """Read the configuration file."""
        file_path = os.path.join(os.getcwd(), "star.json")
        with open(file_path, "r") as file:
            self.config = json.loads(file.read())


    def display_version(self) -> None:
        """Display the version of Star."""
        print(f"Star CLI - Version {__version__}")

    
    def display_script_list(self) -> None:
        """Display a list of all commands in the star.json file."""
        script_list = self.config.get("scripts", {}).keys()
        if script_list:
            console.secondary("Available scripts:")
            for script_name in script_list:
                print(f" - {script_name}")
        else:
            console.secondary("No scripts found in star.json")


    def run_script(self, script_name: str) -> None:
        """Run the specified script."""
        try:
            scripts = self.config["scripts"].get(script_name)

            if isinstance(scripts, str):
                # Display the command.
                console.secondary(f"$ {scripts}")

                # Run the single command in the terminal.
                os.system(scripts)
            elif isinstance(scripts, list):
                # Display the commands.
                console.secondary(f"$ {' && '.join(scripts)}")

                # Run the multiple commands in the terminal.
                for script in scripts:
                    os.system(script)
            else:
                console.error("error", end=" ")
                print("Cannot convert an unknown type to a primitive value")
        except KeyError:
            console.error("error", end=" ")
            print(f"Command \"{script_name}\" not found.")

版本.py

__version__ = "0.1.0"

主要.py

from .cli import CLI


if __name__ == "__main__":
    CLI()

设置.py

from setuptools import setup
from src.star.version import __version__


setup(
    name="python-star",
    version=__version__,
    license="MIT",
    description="A command-line tool for simplifying project setup and development tasks.",
    long_description=open("README.md").read(),  # Make sure to create a README.md file
    long_description_content_type="text/markdown",
    packages=["star"],
    package_dir={"": "src"},
    entry_points={
        "console_scripts": [
            "star=star.__main__:CLI",
        ],
    },
    keywords=[
        "CLI",
        "project setup",
        "testing",
        "development",
        "automation",
        "scripting",
        "workflow",
        "convenience",
        "productivity",
        "deployment",
        "utility",
        "developer tool",
        "single command",
    ],
    install_requires=[
        "console-py==0.1.3",
    ],
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
)

环境:

  • 操作系统:Windows 10
  • Python版本:3.11.4
  • PyInstaller版本:5.13.0

预期输出:

我希望包的行为方式与直接执行脚本或使用 PyInstaller 创建独立可执行文件时的行为方式相同。每个命令后不应显示不需要的消息

任何有关如何解决此问题的见解或建议将不胜感激。谢谢!

python package exe
1个回答
0
投票

A- 尝试使用 pip install -e 重新安装软件包

B- 尝试验证端点

入口点={ “控制台脚本”:[ "star=star.main:CLI.run_script", # 直接指定可调用 ], }

© www.soinside.com 2019 - 2024. All rights reserved.