所以我正在编写一些在程序中使用的模块 但是我在使用我在模块ex中定义的变量时遇到了困难:
a.py
body {
display: grid;
grid-template-columns: repeat(8,1fr);
grid-template-rows: auto;
grid-gap: 10px;
}
#box-0 {
grid-row: 1;
grid-column: 1/10;
background-color: blue;
}
.box-1 {
grid-row: 2/span 2;
grid-column: 1/2;
background-color: blue;
}
.box-2 {
grid-row: 4/span 2;
grid-column: 1/2;
background-color: blue;
}
.box-3 {
grid-row: 2/span 1;
grid-column: 2/10;
background-color: blue;
}
.box-4 {
grid-row: 3/span 3;
grid-column: 2/8;
background-color: blue;
}
.box-5 {
grid-row: 3/span 3;
grid-column: 8/10;
background-color: blue;
}
.box-6 {
grid-row: 6/span 2;
grid-column: 1/4;
background-color: blue;
}
.box-7 {
grid-row: 6/span 2;
grid-column: 4/7;
background-color: blue;
}
.box-8 {
grid-row: 6/span 2;
grid-column: 7/10;
background-color: blue;
}
b.py
def func():
#do something to set the variable var
var = randomValue
我将var设置为global,但仍未定义var。
所有这些答案看起来都很棒,但主题都不适用于我的剧本。所以这是模块,也许你可以告诉我如何将from a import func
func()
#how do i get var
放到另一个脚本中:
time_converted
答案 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。
答案 1 :(得分: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
答案 2 :(得分: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)
感谢帮助人员