How to import variable values from one python script to another

Question:

I have three python scripts START.py, credentials.py and ask_LDAP.py. The first is in the Szperacz_2.0 directory, which is the root directory for the rest, the next two are in the src directory, one level down.

Szperacz_2.0
|
| START.py
|- src
|   | - credentials.py
|   | - ask_LDAP.py

When I run ask_LDAP.py everything works and the console asks for login and password and then prints the entered characters. The problem is when I run START.py, the console asks for login and password and then returns an error:

Traceback (most recent call last):
  File "d:Szperacz_2.0START.py", line 10, in <module>
    import credentials
ModuleNotFoundError: No module named 'credentials'

I apologize in advance if the problem is trivial but I am a beginner in python.

my scripts:

./START.py

import os

# --- Clearing the Screen
os.system('cls')

path = "./src/credentials.py"
exec(open(path).read())

path = "./src/ask_LDAP.py"
import credentials
exec(open(path).read())

./src/credentials.py

import getpass
login = input("Login: ")
password = getpass.getpass()

./src/ask_LDAP.py

import credentials

login = credentials.login
password = credentials.password

print("login from credentials.py: " + login)
print("passwd from credentials.py: " +password)
Asked By: Kubix

||

Answers:

Python does not know what you mean by "credentials", since the file is not in the same directory. You can add a file named

__init__.py

to in your directory "src", therefore making it a package. Then you can modify your import in START.py to

from src import credentials

which should yield the desired result. Subsequently you will run into another error, due to the call to exec(). You should remove this part and use a better way as in: How can I make one python file run another?

Answered By: mafe
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.