简体   繁体   中英

Correct way to import functions from file in python3

I'm building a simple python3 CLI for some scripting. 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 :

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

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

(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. What is the correct way to import the function with python3+ (I don't care about 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. 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

python -m pycli.cli

So what I needed is to create a proper package with the 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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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