Skip to content
Advertisement

Trying to import a script from other code

I need help to import a script, i did 2 codes, the first is a test with some prints and in the second i try to import them:

Code 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')

Code 2

import os

attempt = os.system(r"python C:UsersGabriPycharmProjectspythonProjectImagens.py")

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

But in code 2, when i did os.system(r"python C:UsersGabriPycharmProjectspythonProjectImagens.py") nothing happen. Someone can help me to import this code? ;-;

1° Code is in C:UsersGabriPycharmProjectspythonProject

2° in C:UsersGabriPycharmProjectspythonProjectPráticaVamove

Advertisement

Answer

If you want to keep the files where they are,
You should by able to do this:

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)

And then run your commands like this:

Imagens.first()
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement