简体   繁体   English

从 PyCharm 识别但不通过命令行识别的包中导入

[英]Import from my package recognized by PyCharm but not by command line

I've created the following package tree:我创建了以下包树:

/main_package
    /child_package
    version.py

where version.py contains a single string variable (VERSION)其中 version.py 包含单个字符串变量 (VERSION)

Inside my script in child package I'm importing version.py by the following line:在子包中的脚本中,我通过以下行导入 version.py:

from main_package.version import VERSION

While I'm running the code from PyCharm everything works great, however when I'm running the code via the command line I'm getting the following error message:当我从 PyCharm 运行代码时,一切正常,但是当我通过命令行运行代码时,我收到以下错误消息:

C:\Users\usr\PycharmProjects\project\main_package\child_package>python script.py
Traceback (most recent call last):
File "script.py", line 2, in <module>
from main_package.version import VERSION
ModuleNotFoundError: No module named 'main_package'

I've found in the internet that I might need to add my package to the python path, however it doesn't seems to work for me我在互联网上发现我可能需要将我的包添加到 python 路径,但它似乎对我不起作用

PyCharm sets the Python Path at the root of the project (by default). PyCharm 将 Python 路径设置在项目的根目录(默认情况下)。 To mimic this in a quick'n'dirty fashion, you just need to do this once in your shell session before invoking python whatever :要以快速的'n'dirty 方式模仿它,您只需要在调用python whatever之前在 shell 会话中执行一次:

set PYTHONPATH=C:\Users\usr\PycharmProjects\project

The pythonic way is to have a setup.py file to install your project in the system (check python Minimal Structure ): pythonic 的方法是有一个setup.py文件来在系统中安装你的项目(检查python Minimal Structure ):

from setuptools import setup

setup(name='main_package',
      version='0.1',
      description='main package',
      license='MIT',
      packages=['main_package'],
      zip_safe=False)

Then you install it as follow:然后按如下方式安装它:

  • python setup.py install for global installation python setup.py install进行全局安装

OR要么

  • python setup.py develop for local installation in editable mode python setup.py develop以可编辑模式进行本地安装

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

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