2013-06-30 67 views
1

我想从test1.py中的test.py中定义调用Branchname并运行到以下错误,任何人都可以提供输入吗?在不同的python模块中调用参数

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 

运行到以下错误

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 
+0

您在这里有一个圆形的进口,这是从来没有好。代码是这样分裂的吗? –

+0

@BurhanKhalid - 我的目标是打印从test1.py传递给test.py的BranchName。 – user2341103

+1

你没有在这里传递任何东西。 –

回答

1

我的目标是打印BRANCHNAME通过从test1.py

到test.py了。如果这是你的话,那么你的文件名是相反的。此外,你没有传递任何东西(你应该,而不是玩global)。

test1.py,计算BranchName,然后传递main方法从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() 

test.py,你干脆:

def main(branch_name): 
    print('In test.py, the value is: {0}', branch_name) 
+0

is there一种在上面的脚本中使用“if __name__ =='__main__':”在test.py中获得此方法的方法。 – user2341103

+0

您可以将该行放入要调用的任何脚本中作为起点。设置'ScriptDir'的脚本是起点,这就是它在'test1.py'中的原因。如果你把这行放在'test.py'中,你会得到一个错误,因为你没有任何东西要传递给'main'('ScriptDir'不会被设置)。 –

4

main()实际上并没有被调用您的test.py,因为__name__ != '__main__'

如果您打印__name__,它实际上是test

这就是为什么许多脚本具有if __name__ == '__main__'的原因,因此如果它被导入,则整个代码不会运行。

为了解决这个问题,你必须做两件事情:

  • 你可以只取出if __name__ == '__main__':test.py,只是用main()

  • 取代它没有必要import test1.py在你的测试。这样做实际上在test1.py中运行main(),因此会引发错误,因为test.BranchName尚未定义。

    • 但是,如果您必须导入test1.py,实际上你可以把一个if __name__ == '__main__'在那里,所以当你从test.py导入它,它不会运行。
+0

我该如何解决? – user2341103

+0

@ user2341103我编辑了我的回答 – TerryA

+0

@LennartRegebro其实,我已经编辑了我的回答,关于这个 – TerryA

相关问题