0

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:\Users\Gabri\PycharmProjects\pythonProject\Imagens.py")

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

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

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

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

1
  • 3
    Python documentation has a section on modules and how to import them into your code. Take a look here. docs.python.org/3/tutorial/modules.html. Also in your question you don't tell us what the file names are. Python uses file names and directory names for importing. Commented Jun 4, 2021 at 18:16

2 Answers 2

0

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()
Sign up to request clarification or add additional context in comments.

3 Comments

I run your code and this happen NameError: name 'foo' is not defined what's 'foo'?
Yes, sorry, I fixed the code. It should work now
Forgets, i just add .third() to Imagens.phrase and it worked hahaha
0

The easiest is if you put both in the same folder and make that folder a python directory from which you can import your other code as modules. All you need for that is a file in the folder containing a blank __init__.py file. Then you can import it to another code file in the same folder using

from folder_name import Imagens

and you should be able to use Imagens functions like any other module

Ex: Imagens.first()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.