2016-07-30 41 views
1

我試圖在兩個不同的Python腳本之間傳遞信息。他們是很長,所以爲了簡化的目的,這裏有我在那裏遇到同樣問題的其他兩個腳本:如何在兩個不同的Python腳本之間傳遞變量

a.py

f = open('test.txt', 'w+') 
num = int(raw_input('How many are there: ')) 
tipe = raw_input('What kind are they: ') 

if __name__ == '__main__': 
    from b import fxn 

    for x in xrange(num, num+11): 
     fxn() 
     num = x 

    f.close() 

b.py

from a import num, tipe 

def fxn(): 
    print num, tipe 
    f.writelines(str(num)+', '+tipe) 

我問對於num和tipe兩次,則第二次輸入將被打印11次。

我該如何使a.py中的變量/文件傳遞給b.py,在b.py中編輯/打開/處理,然後傳遞迴/在a.py中關閉?

而且,爲什麼我問NUM和TIPE兩次,然後如果 ==「主要」下的代碼:運行?

+0

功能可以帶參數。您被要求輸入兩次的原因是那些IO操作在全局範圍內,並且每次輸入a時都會執行。 – mljli

回答

0

在Python腳本之間傳遞變量時,請記住當您調用腳本時,調用腳本可以訪問被調用腳本的名稱空間。

話雖這麼說,你可以試試這個:用代碼

from __main__ import * 

這將授予訪問命名空間主叫腳本(變量和函數)啓動調用的腳本。由於這些文件實際上並不是您剛纔所說的那些文件,所以我會將其留待您將其應用到真實文件中,希望這會有所幫助。

0

你可以通過他們通過功能

a.py

f = open('test.txt', 'w+') 
num = int(raw_input('How many are there: ')) 
tipe = raw_input('What kind are they: ') 

if __name__ == '__main__': 
    from b import fxn 

    for x in xrange(num, num+11): 
     fxn(num, tipe, f) # Pass parameters num, tipe and file handle 
     num = x 

    f.close() 

b.py

# from a import num, tipe --> **This is not required** 

# receive inputs 
def fxn(num, tipe, f): 
    print num, tipe 
    f.writelines(str(num)+', '+tipe) 

執行a.py將導致

3 fruits 
3 fruits 
4 fruits 
5 fruits 
6 fruits 
7 fruits 
8 fruits 
9 fruits 
10 fruits 
11 fruits 
12 fruits 

3水果打印兩次,因爲你先調用函數,然後你增加num(通過重新分配)。相反,你可以有你的a.py下面有3種水果印刷只有一次:

f = open('test.txt', 'w+') 
num = int(raw_input('How many are there: ')) 
tipe = raw_input('What kind are they: ') 

if __name__ == '__main__': 
    from b import fxn 

    for x in xrange(num, num+11): 
     fxn(x, tipe, f) # Pass parameters num, tipe and file handle 

    f.close() 
相關問題