在Python包中测试可执行文件

2024-04-25 18:08:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一名Ruby程序员,正在开发我的第一个Python包(我们称之为foo)。它的主要用途是作为命令行工具。我指定它应该作为setup.py中的可执行文件安装,使用:

setup(
    entry_points={
        'console_scripts': [
            'foo = foo.cli:main'
        ]
    }
)

foo/cli.py包含:

import foo

def main():
    # program logic here

if __name__ == '__main__':
    main()

cli.py需要引用在foo/__init__.py中定义的foo.__version__,但是当我在本地运行python foo/cli.py来测试CLI时,import foo会引发ImportError: No module named foo。我怎样才能让Python看到客户端在foo包的上下文中运行这样的单个文件时?我的方法完全错了吗?您通常如何在本地测试用setuptools的入口点定义的可执行文件?你知道吗


Tags: 工具命令行pyimport可执行文件cli定义foo
2条回答

您缺少修改sys.pathPYTHONPATH变量以同时包含foo/所在的目录。你知道吗

在运行客户端文件执行以下操作

codepython@vm-0:~/python/foo$ PYTHONPATH=$PYTHONPATH:~/python/;export PYTHONPATH

在我的设置中,foo/出现在~/python中,foo/中的\em>init\upy告诉python解释器,foo是一个包,而不是一个普通目录。你知道吗

现在您可以cd进入foo/目录,然后运行python cli.py。您将能够访问foo包方法和函数。你知道吗

或者,在main()中,您可以首先修改sys.path,以附加包含foo/的目录,然后执行其余的逻辑

引用Python documentation on Modules

When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:

the directory containing the input script (or the current directory). PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH). the installation-dependent default. After initialization, Python programs can modify sys.path. The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. This means that scripts in that directory will be loaded instead of modules of the same name in the library directory. This is an error unless the replacement is intended. See section Standard Modules for more information.

在包中,可以直接导入__init__,然后使用as重命名。试试这个

import __init__ as foo

代替

import foo

相关问题 更多 >