尝试从其他代码导入脚本

Trying to import a script from other code

我需要帮助来导入脚本,我做了 2 个代码,第一个是测试一些打印件,第二个我尝试导入它们:

代码 1

# I make some print's to try import and show if it works

def first():
    print('Test')


class phrase:
    def second():
        print('Hello')

    def third():
        print('World')

代码 2

import os

attempt = os.system(r"python C:\Users\Gabri\PycharmProjects\pythonProject\Imagens.py")

# Obviously isn't works =(
attempt.first()

但是在代码 2 中,当我执行 os.system(r"python C:\Users\Gabri\PycharmProjects\pythonProject\Imagens.py") 时没有任何反应。 有人可以帮我导入这段代码吗? ;-;

1° Code is in C:\Users\Gabri\PycharmProjects\pythonProject

2° in C:\Users\Gabri\PycharmProjects\pythonProject\Prática\Vamove

最简单的方法是将两者放在同一个文件夹中,并将该文件夹设为 python 目录,您可以从中将其他代码作为模块导入。您所需要的只是文件夹中包含空白 __init__.py 文件的文件。然后你可以使用

将它导入到同一文件夹中的另一个代码文件

from folder_name import Imagens

而且您应该能够像使用任何其他模块一样使用 Imagens 函数

例如:Imagens.first()

如果您想将文件保留在原处,
你应该能够做到这一点:

import importlib.util
spec = importlib.util.spec_from_file_location(
    "name", "C:\Users\Gabri\PycharmProjects\pythonProject\Imagens.py")
Imagens = importlib.util.module_from_spec(spec)
spec.loader.exec_module(Imagens)

然后 运行 你的命令是这样的:

Imagens.first()