将文件导入为Python中的模块

发布于 2025-02-12 05:50:50 字数 571 浏览 1 评论 0原文

我想制作一个CMD工具。我创建了两个文件,一个名为main.py,另一个名为version.py 在同一目录中有

import os

def pyVersion():
    os.system("python --version")

版本

import version

version.pyVersion()

。印刷:


  File "C:\Users\User\PycharmProjects\cmd tool\main.py", line 1, in <module>
    import version
ModuleNotFoundError: No module named 'version'

I wanted to make a cmd tool. I created two files, one named main.py, and the other named version.py
there are in the same directory

version.py:

import os

def pyVersion():
    os.system("python --version")

main.py:

import version

version.pyVersion()

I think it should work, but when I run main.py, it prints:


  File "C:\Users\User\PycharmProjects\cmd tool\main.py", line 1, in <module>
    import version
ModuleNotFoundError: No module named 'version'

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

是你 2025-02-19 05:50:50

通常,python应该使用文件夹c:\ user \ user \ user \ pycharmprojects \ cmd tool \搜索导入的模块,即使在列表sys.path上,您也可以使用此文件

夹列表上没有此文件夹,然后您可以在导入模块之前手动添加它。

import sys

# add at the end of list
#sys.path.append(r'C:\Users\User\PycharmProjects\cmd tool\')

# add at the beginning of list
sys.path.insert(0, r'C:\Users\User\PycharmProjects\cmd tool\')

import version

# ... code ...

为了使其更普遍,您可以使用OS获取此文件夹而无需硬编码

import os

BASE = os.path.dirname(os.path.abspath(__file__))
print('BASE:', BASE)

import sys

sys.path.insert(0, BASE)

import version

# ... code ...

Normally Python should use folder C:\Users\User\PycharmProjects\cmd tool\ to search imported modules and you may have this folder even on list sys.path

But if it doesn't have this folder on list then you may add it manually before importing module.

import sys

# add at the end of list
#sys.path.append(r'C:\Users\User\PycharmProjects\cmd tool\')

# add at the beginning of list
sys.path.insert(0, r'C:\Users\User\PycharmProjects\cmd tool\')

import version

# ... code ...

To make it more universal you can use os to get this folder without hardcoding

import os

BASE = os.path.dirname(os.path.abspath(__file__))
print('BASE:', BASE)

import sys

sys.path.insert(0, BASE)

import version

# ... code ...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文