Reputation: 1
To make a clear structure for my project I try to keep different parts in different file.py. And I use one main.py to start the scripts together(threaded). Now I want to get one datetime.datetime variable into the other script.
For example :
#main.py
import file1
import file2
if __name__=='__main__':
p1 = Process(target = file1.a)
p1.start()
time.sleep(1)
p2 = Process(target = file2.b)
p2.start()
#file1.py
def a():
global t1
t1 = datetime.datetime(example date)
#file2.py
def b():
print(t1)
The error I get is the following :
Traceback (most recent call last):
File "location\main.py", line 7, in <module>
import test2
File "location\file2", line 3, in <module>
b()
File "location\file2", line 2, in b
print(t1)
NameError: name 't1' is not defined
What am I doing wrong? Importing file1 in file 2 doesn't seem to work too. Should I just be putting all the scripts in one file?
If I miss any info, just ask:) Thanks!
Upvotes: 0
Views: 47
Reputation: 861
Try this:
t1=0
def a():
t1=datetime.datetime(example date)
setting t1
outside of the method definition should make it accessible when the file is imported (file1.t1
, obviously).
Upvotes: 0
Reputation: 145
As the traceback says, error comes from the fact that global t1
is undefined.
If you posted the entire code, then the error is in
#file1.py
def a():
global t1 # Python interpreter can not find this variable.
t1 = datetime.datetime(example date)
However if you want to share ressources between processes, then consider the multiprocessing module.
Upvotes: 2