2017-08-05 135 views
1

所以在寫一些模塊的程序 內使用,但使用i中的模塊的前內定義變量時遇到的困難:如何訪問在模塊內部定義的變量?

a.py

def func(): 
    #do something to set the variable var 
    var = randomValue 

b.py

from a import func 
func() 
#how do i get var 

我將var設置爲全局,但仍未定義var。

所有這些答案看起來不錯,但沒有任何主題爲我的腳本工作。因此,這裏的模塊,也許你能告訴我怎麼去time_converted到另一個腳本:

from ib.opt import Connection, message 
import time 
import datetime 

list_time = [] 
global time_converted 
def reply_handler(msg): 
    if msg.typeName == "currentTime": 
     time = msg.time 
     list_time.append(time) 
     time_converted = (datetime.datetime.fromtimestamp(int("%s"% time 
                  )).strftime('%Y-%m-%d %H:%M:%S')) 
     return time_converted 



def GetTime(): 
    conn = Connection.create(port=7496, clientId=100) 
    conn.registerAll(reply_handler) 
    conn.connect() 
    conn.reqCurrentTime() 
    while True: 
     if len(list_time) == 0: 
      pass 
     elif len(list_time) == 1: 
      break 
      conn.disconnect() 
+3

除非你定義''的外FUNC var'()'或返回它,你不能 –

+0

「所有這些答案看起來不錯,但沒有一個主題適用於我的腳本「究竟發生了什麼問題?你有錯誤信息嗎?你有錯誤的價值嗎?請具體說明。 – Xukrao

+0

我只是得到「none」而不是任何值 – TB1

回答

2

a.py

from random import random 

def func(): 
    var = random() 
    return var 

x = func() 

b.py

from a import func,x 

print (func(), x) 

從執行b.py輸出:

0.2927063452485641 0.8207727588707955 

編輯,響應於修改的問題

reply_handler本身收到回調來處理它使用另一個回調到它的結果報告給代碼的時間。

使用一個回調函數..

1.py

from main import receiver 

def GetTime(): 
    reply_handler('this is the time') 

def reply_handler(msg): 
    receiver(msg) 

GetTime() 

main.py

def receiver(message): 
    print (message) 

輸出:

this is the time 
+0

我對它的工作對我來說,但是當我試着用腳本我只是把它給了我「沒有,沒有」 – TB1

+0

請參閱編輯。 –

+0

你可以考慮這個選擇。 –

2

你定義一個函數內部的變量。要使該變量的值在函數外部可用,您需要使用return語句。舉個例子:

a.py

def func(): 
    # do something to set the variable `var` 
    var = 10 

    return var 

b.py

from a import func 

# to get var 
var = func() 
print('The value of var is:', var) 

有關的功能和return語句更多解釋見here

+0

好吧,讓我們說,在a.py var =「10」裏面如何在b.py中打印10。當我打印var時,它只是給我None。 – TB1

+0

@TarikBlaoui嘗試運行剛剛更新的代碼示例。 – Xukrao

+0

好吧我要去適應它到我的腳本,並看到 – TB1

0

所以這就是我應該這樣做的:

GetPrice。PY

from ib.opt import Connection, message 
import datetime 

    list_time = [] 
    def reply_handler(msg): 
     if msg.typeName == "currentTime": 
      time = msg.time 
      list_time.append(time) 
      global time_converted 
      time_converted = (datetime.datetime.fromtimestamp(int("%s"% time 
                   )).strftime('%Y-%m-%d %H:%M:%S')) 


    def GetTime(): 
     conn = Connection.create(port=7496, clientId=100) 
     conn.registerAll(reply_handler) 
     conn.connect() 
     conn.reqCurrentTime() 
     while True: 
      if len(list_time) == 0: 
       pass 
      elif len(list_time) == 1: 
       break 
       conn.disconnect() 

     return time_converted 

Main.py

from GetRealtime import GetTime 

x = str(GetTime()) 
print (x) 

感謝您的幫助球員

相關問題