简体   繁体   中英

Importing custom python module

I am creating pip package and before submitting I would like to try it. For simplification, lets assume that python script looks like this:

def foo():
    print("Hello World!")

My setup.py containing metadata looks like:

#!/usr/bin/env python3
from setuptools import setup, find_packages

    setup(
        name="test_super_secret",
        version="1.0",
        description="testing pip version 1",
        packages=find_packages(),
    )

I have compiled script using Wheel , so that I'm able to install it via pip :

user@pc:$ python -m pip install dist/test_super_secret-1.0-py2-none-any.whl 
Processing ./dist/test_super_secret-1.0-py2-none-any.whl
Installing collected packages: test-super-secret
Successfully installed test-super-secret-1.0

However, when I'm not able to import such module from python:

    >>> import test-super-secret
  File "<stdin>", line 1
    import test-super-secret
               ^
SyntaxError: invalid syntax

What am I doing wrong? Should I import it in another way or should I change setup so that it would be possible to import module?

EDIT: Module can not be imported even if it is called testsupersecret in the setup.py :

>>> import testsupersecret
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named testsupersecret

test-super-secret is not a valid module name -- you can't have hyphens in the module names (or variables), python thinks this is a minus sign, that's why you get invalid syntax. You should use underscores (which you probably already are using based on your setup.py -- name="test_super_secret" , just try importing test_super_secret ).

(Python packages can have hyphens in the name, that's probably where the confusion comes from. So test-super-secret is a valid name for pip package, but the module must be named test_super_secret .)

It looks like I did not have correct folder structure to get modules as a library. Once I created directory containing __init__.py and move my script to that directory, I was able to import module like import <MyLibrary>.<my_script_name>

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