将值传递给另一个python模块

时间:2013-06-30 17:12:14

标签: python

我正在以python test.py ab_mr1运行脚本,"ab_mr1"的输出应为branch_name,但它打印为emtpy值,任何想法为什么?

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')

1 个答案:

答案 0 :(得分:3)

你很困惑。您正在运行test.py不是 test1.py

运行test1.py让其致电test.main()。由于您正在运行test.py,因此__main__阻止正在运行且branch_name为空字符串。

您的代码正常工作Just Fine:

$ 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