Reputation: 2433
I am trying to call Branchname defined in test.py from test1.py and running into following error,can anyone provide inputs?
test.py
import test1
import os
import sys
def main():
#initialize global variables & read CMD line arguments
global BranchName
ScriptDir = os.getcwd()
print ScriptDir
BranchName = sys.argv[1]
print "BranchName"
print BranchName
#Update input file with external gerrits, if any
print "Before running test1"
test1.main()
print "After running test1"
if __name__ == '__main__':
main()
test1.py
import test
def main ():
print test.BranchName
Running into following error
BranchName
ab_mr2
Before running test1
Traceback (most recent call last):
File "test.py", line 18, in <module>
main()
File "test.py", line 14, in main
test1.main()
File "/local/mnt/workspace/test1.py", line 3, in main
print test.BranchName
AttributeError: 'module' object has no attribute 'BranchName
Upvotes: 1
Views: 65
Reputation: 174624
my goal is to print BranchName passed to test.py from test1.py
If this is your case, then your file names are reversed. Also, you aren't passing anything around (which you should, instead of playing with global
).
In test1.py
, calculate BranchName
, and then pass it to the main
method from test
.
import os
import sys
import test
def main():
ScriptDir = os.getcwd()
print ScriptDir
BranchName = sys.argv[1]
print "BranchName"
print BranchName
#Update input file with external gerrits, if any
print "Before running test1"
test.main(BranchName) # here I am passing the variable
print "After running test1"
if __name__ == '__main__':
main()
In test.py
, you have simply:
def main(branch_name):
print('In test.py, the value is: {0}', branch_name)
Upvotes: 1
Reputation: 59974
main()
does not actually get called in your test.py, because __name__ != '__main__'
.
If you print __name__
, it is actually test
.
This is a reason why many scripts have the if __name__ == '__main__'
, so if it is imported, the whole code isn't run.
To fix this, you have to do two things:
You can just remove the if __name__ == '__main__':
in your test.py
, and just replace it with main()
There is no need to import test1.py
in your test. In doing so, this is actually running main()
in your test1.py
, and will thus raise an error because test.BranchName
hasn't even been defined yet.
test1.py
, you can actually put an if __name__ == '__main__'
in there, so when you import it from test.py
, it will not run.Upvotes: 4