简体   繁体   English

在python3中从文件导入函数的正确方法

[英]Correct way to import functions from file in python3

I'm building a simple python3 CLI for some scripting.我正在为一些脚本构建一个简单的 python3 CLI。 I have troubles importing my own functions located in files that are in the same modules.我在导入位于相同模块中的文件中的自己的函数时遇到了麻烦。

My file structure is我的文件结构是

pycli/
├── README.md
├── pycli
  ├── __init__.py
  ├── cli.py
  └── funcmodule.py

funcmodule.py : funcmodule.py :

def my_function(word):
    print("Hello %s" % word)

cli.py : cli.py :

#!/usr/bin/env python3

from pycli.funcmodule import my_function


def main():
    my_function('hello world')


if __name__ == '__main__':
    main()

When I run ./pycli/cli.py from the command line I get当我从命令行运行./pycli/cli.py ,我得到

(venv) ➜  ./pycli/cli.py 
Traceback (most recent call last):
  File "./pycli/cli.py", line 3, in <module>
    from pycli.funcmodule import my_function
ModuleNotFoundError: No module named 'pycli'

When I run the cli.py from PyCharm or in Visual Studio Code, it works correctly.当我从 PyCharm 或 Visual Studio Code 运行cli.py ,它可以正常工作。 What is the correct way to import the function with python3+ (I don't care about python2)?用python3+导入函数的正确方法是什么(我不关心python2)?

This is a mismatch between how you're running the program and how your imports are set up.这是您运行程序的方式与设置导入方式之间的不匹配。 Your imports are set up as if there's a package involved, but you're running the program like there's no package.您的导入被设置为好像涉及一个包,但您正在运行该程序,就像没有包一样。

The way you're running your program, the contents of the inner pycli folder are all top-level modules, and there is no pycli package.你运行程序的方式, pycli文件夹的内容都是顶层模块,没有pycli包。 To run your program as a package submodule, you need to do so from somewhere the pycli package is importable (which, as things are, would be inside the outer pycli folder, but could be anywhere if you installed your package), and you need to run要将您的程序作为包子模块运行,您需要从pycli包可导入的某个地方执行此pycli (实际上,该包位于外部pycli文件夹内,但如果您安装了包,则可以在任何位置),并且您需要跑步

python -m pycli.cli

So what I needed is to create a proper package with the setup.py :所以我需要的是用setup.py创建一个合适的包:

from setuptools import setup
setup(
    name = 'pycli',
    version = '0.1.0',
    packages = ['pycli'],
    entry_points = {
        'console_scripts': [
            'pycli = pycli.cli:main'
        ]
    })

in order to run it from the terminal为了从终端运行它

pip3 install .

pycli
Hello hello world 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM