0

how can i set a global variable, from a other file from other directory?

I would like to take the variable aaid into test.py and the variable bbid from test.py print in test2.py

Structure:

d:\test\main.py
d:\test\a\test.py
d:\test\b\test2.py

main.py:

# import relevant files
import sys, os, subprocess
while (True):
# The menu
print("MENU")
print(" 1. Librarian")
try:
    choice = int(input("Select who you are (choose a number): "))
except ValueError:
    print("you have not entered a numerical input! \nplease enter a number")

# Librarian choice 

if choice == 1:
    while (True):
        # Handling Value Error
        try:
            aaid = input("\nID? :")
        except ValueError:
            print("Error! Please enter a numerical input")
        else:
            os.chdir("a/")
            subprocess.call('python test.py', shell=True)
            break

test.py

print(aaid)
bbid = x500

test2.py

print(bbid)

error:

Traceback (most recent call last):
File "test.py", line 2, in <module>
print(aaid)
NameError: name 'aaid' is not defined   

python 3.8.2 on windows 10

kuck
  • 97
  • 6
  • 1
    Usually if you want to pass data between files, you can import the file `import test`, and then access variables from it via `test.aaid`. You'll need to look at how to import other files within subdirectories, so I recommend searching "relative imports" or looking at [this answer](https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time) – dwb Apr 08 '20 at 17:44
  • the variable aaid is an input, how do I set it globally available? or how do I import them in test.py? – kuck Apr 08 '20 at 18:20
  • You shouldnt be designing your program this way to begin with. In any case, Python doesn't have true globals, but rather, module-level globals. You import modules and use the variables on the module. – juanpa.arrivillaga Apr 08 '20 at 18:30

0 Answers0