这是我在 oandapy 和 PyQt 时遇到问题的一个非常基本的例子:我无法让它们一起工作。
目标是激活GUI窗口并获取数据流(在此示例中,数据流将在终端窗口中打印)。
当我激活oandapy流式传输(参见stream.rates(account, instruments="EUR_USD")
)时,PyQt GUI(此示例中为,它是一个空窗口)不会出现。在终端窗口中,您可以看到数据流。
任何帮助?
提前谢谢你,
吉尔伯托
P.S。要运行此示例,您必须根据您的Oanda API帐户更改account
和access_token
设置。
# --- GUI
import sys
from PyQt5 import QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.resize(400, 300)
# --- OANDA
import oandapy
class Streamer(oandapy.Streamer):
def __init__(self, *args, **kwargs):
super(Streamer, self).__init__(*args, **kwargs)
def on_success(self, data):
print(data, "\n")
account = "12345"
stream = Streamer(environment="practice", access_token="abc123-def456")
# --- MAIN
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
print('Start')
#stream.rates(account, instruments="EUR_USD") # if commented, the GUI window appears, otherwise it will not
sys.exit(app.exec_())
感谢@ekhumoro的建议我修改了以下代码(只是一个例子,不需要Oanda凭证)。
# --- GUI
import sys
from PyQt5 import QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.resize(400, 300)
# --- TEST LOOP
import time
def loop(): # this is a test function
while 1:
print('.', sep=' ', end='', flush=True) # print "." in line
time.sleep(1) # pause 1 sec
# --- THREADING
from threading import Thread
# --- MAIN
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
print('\n\n BEFORE \n\n')
# loop() # this blocks
Thread(target=loop).start() # this doesn't block, check the terminal
print('\n\n AFTER \n\n')
sys.exit(app.exec_())
# --- GUI
import sys
from PyQt5 import QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.resize(400, 300)
# --- OANDA
import oandapy
class Streamer(oandapy.Streamer):
def __init__(self, *args, **kwargs):
super(Streamer, self).__init__(*args, **kwargs)
def on_success(self, data):
print(data, "\n")
def DataStream():
account = "..."
stream = Streamer(environment="practice", access_token="...")
stream.rates(account, instruments="EUR_USD")
# --- THREADING
from threading import Thread
# --- MAIN
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
print('Start')
Thread(target=DataStream).start() # this doesn't block
sys.exit(app.exec_())