Reputation: 67
I have two files. The first file, we'll call it "a.py". The second, "b.py".
Here's an example of "a.py":
#!/usr/bin/env python
# coding=utf-8
CHOOSE = input ('''
\033[1;35m choose 1 or 2:\033[0m
1)tom
2)jack
''')
a = 666
b = "bbb"
def f():
print("this is a test")
return "function"
if __name__ == '__main__':
if CHOOSE == '1':
username = 'tom'
print(username)
elif CHOOSE == '2':
username = 'jack'
print(username)
else:
print('wrong choice,scipt is exit...')
Here's an example of "b.py":
#!/usr/bin/env python
# coding=utf-8
import a
from a import b,f,CHOOSE,username
a = a.a
f()
print(b,a,CHOOSE,username)
when i run python b.py
,system feedback error:
wherem am i wrong?how to fix it?
Upvotes: 0
Views: 214
Reputation: 3604
Because this snippet:
if __name__ == '__main__':
if CHOOSE == '1':
username = 'tom'
print(username)
elif CHOOSE == '2':
username = 'jack'
print(username)
else:
print('wrong choice,scipt is exit...')
Will get executed only if the a.py
run as the main python file not imported from other module, so username
will not be defined so you can not import it. Here how to fix it:
a.py
:
...
def foo(CHOOSE):
if CHOOSE == '1':
username = 'tom'
elif CHOOSE == '2':
username = 'jack'
else:
username = None
return username
b.py
:
from a import foo
CHOOSE = input ('''
\033[1;35m choose 1 or 2:\033[0m
1)tom
2)jack
''')
username = foo(CHOOSE)
if username:
print(username)
else:
print('Wrong choice')
Explanation: First you need to extract the code that calculate the name into something reusable. Function are meant for code reusability so I defined one which take one parameter and it return the corresponding value. This function is then used (imported then invoked) in b.py
.
Usually if __name__ == '__main__':
is placed in the module that you consider your entry-point, so if you want to use it maybe b.py
is a better place.
Upvotes: 2
Reputation: 24691
The block if __name__ == '__main__'
only triggers if the script is run with a.py
being the main module (e.g. you ran it using the command python a.py
). If anything else was used as the main module, and a
was imported, then this condition is not met and the code inside of it does not run.
The variable username
is created and added to a
's namespace in the if __name__ == '__main__'
block. When you do python b.py
, the code inside this block does not execute, and as a result username
never gets added to the namespace. So when you try to import it, immediately after loading the file a
, you get an error saying that the 'username'
doesn't exist - it was never created.
Upvotes: 0