2013-06-30 75 views
0

我正在運行腳本爲python test.py ab_mr1,輸出應爲"ab_mr1"branch_name,但它是打印爲emtpy的值,爲什麼?將值傳遞給另一個python模塊

test1.py

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

branch_name='' 
def main(branch_name): 
    print('In test.py, the value is: {0}', branch_name) 
if __name__ == '__main__': # need this 
    main(branch_name) 

電流輸出:

('In test.py, the value is: {0}', '') 

預期輸出:

('In test.py, the value is: {0}', 'ab_mr1') 

回答

3

你搞糊塗了。您正在運行test.py,而不是test1.py

運行test1.py讓它調用test.main()。因爲你正在運行test.py它的__main__塊正在運行,並且branch_name是一個空字符串。

您的代碼,否則工作得很好:

$ python test1.py ab_mr1 
/private/tmp 
BranchName 
ab_mr1 
Before running test1 
('In test.py, the value is: {0}', 'ab_mr1') 
After running test1 
+0

你是對的,愚蠢的錯誤...謝謝 – user2341103

相關問題