Python multiprocessing -> can not spawn Process within thread - python-3.6

I Create a thread inside the __main__ function by creating an object that inherits from threading.Thread. Inside its run method i open multiprocessing.Process with a target function that is in global namespace of the module but i get the error:
from multiprocessing import Process, Queue
import threading
def executeTests(ScriptName, Params, MsgQueue, ResultQueue):
...
class TestRunner(threading.Thread):
def __init__(self, tests):
threading.Thread.__init__(self)
...
def run(self):
MsgQueue = Queue()
ResultQueue = Queue()
TestProcess = Process(target=executeTests, args=(ScriptName, Params, MsgQueue, ResultQueue))
TestProcess.start()
...
if __name__ == "__main__":
TestRunner(...).start()
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Program Files\Python36\lib\multiprocessing\spawn.py", line 105, in sp
awn_main
exitcode = _main(fd)
File "C:\Program Files\Python36\lib\multiprocessing\spawn.py", line 115, in _m
ain
self = reduction.pickle.load(from_parent)
AttributeError: Can't get attribute 'executeTests' on <module '__main__' (built-
in)>

I solved it myself.
A join() was missing in main.

Related

How to deploy a FastAPI endpoint using pythonanywhere?

I have been trying to deploy EasyOCR (it's fine if it works on CPU) with FastAPI endpoints such that anyone can use it via https POST request. It runs fine on my local host but when I have been facing challenges in deploying it using pythonanywhere. I added the additional requirements like pip install easyocr, pip install python-multipart==0.0.5.
The following is my code-
import io
import logging
import re
from fastapi import FastAPI, APIRouter, Request, File, UploadFile
from fastapi.responses import FileResponse, StreamingResponse
import easyocr
import PIL
from PIL import Image, ImageOps
import numpy
app = FastAPI()
router = APIRouter()
ocr = easyocr.Reader(["en"])
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("ocr")
#app.get("/")
async def root():
return {"message": "Hello World"}
#app.post("/ocr")
async def do_ocr(request: Request, file: UploadFile = File(...)):
if file is not None:
imgFile = numpy.array(PIL.Image.open(file.file).convert("RGB"))
res = ocr.readtext(imgFile)
# return array of strings
return [item[1] for item in res]
return {"error": "missing file"}
app.include_router(router)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app)
I am getting the error in the logs-
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/somyatomar15/main.py", line 82, in <module>
uvicorn.run(app)
File "/usr/local/lib/python3.10/site-packages/uvicorn/main.py", line 463, in run
server.run()
File "/usr/local/lib/python3.10/site-packages/uvicorn/server.py", line 60, in run
return asyncio.run(self.serve(sockets=sockets))
File "/usr/local/lib/python3.10/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/usr/local/lib/python3.10/asyncio/base_events.py", line 633, in run_until_complete
self.run_forever()
File "/usr/local/lib/python3.10/asyncio/base_events.py", line 600, in run_forever
self._run_once()
File "/usr/local/lib/python3.10/asyncio/base_events.py", line 1896, in _run_once
handle._run()
File "/usr/local/lib/python3.10/asyncio/events.py", line 80, in _run
self._context.run(self._callback, *self._args)
File "/usr/local/lib/python3.10/site-packages/uvicorn/server.py", line 77, in serve
await self.startup(sockets=sockets)
File "/usr/local/lib/python3.10/site-packages/uvicorn/server.py", line 158, in startup
sys.exit(1)
SystemExit: 1

__call__() got an unexpected keyword argument 'metadata' error for Airflow PubSubHook acknowledge method

I am trying to manually acknowledge each PubSub messages in the Python call back method for PubSubPull Operator. I have provided the arguments as per the documentation. However when i am getting errors related to optional "metadata" argument
Scenario 1 - when metadata=[]: Getting error -> call() got an unexpected keyword argument 'metadata'
PubSubHook().acknowledge(subscription=SNOW_SUBSCRIPTION,project_id=PROJECT_ID, ack_ids=ack_id_list, retry=Retry , timeout=10,metadata=[])
**Traceback:**
File "/opt/python3.8/lib/python3.8/site-packages/airflow/providers/google/cloud/operators/pubsub.py", line 785, in execute
ret = handle_messages(pulled_messages, context)
File "/home/airflow/gcs/dags/snow_ticket_creator_1.py", line 70, in print_messages
PubSubHook().acknowledge(subscription=SNOW_SUBSCRIPTION,project_id=PROJECT_ID, ack_ids=ack_id_list, retry=Retry , timeout=10)
File "/opt/python3.8/lib/python3.8/site-packages/airflow/providers/google/common/hooks/base_google.py", line 457, in inner_wrapper
return func(self, *args, **kwargs)
File "/opt/python3.8/lib/python3.8/site-packages/airflow/providers/google/cloud/hooks/pubsub.py", line 561, in acknowledge
subscriber.acknowledge(
File "/opt/python3.8/lib/python3.8/site-packages/google/pubsub_v1/services/subscriber/client.py", line 1270, in acknowledge
rpc(
File "/opt/python3.8/lib/python3.8/site-packages/google/api_core/gapic_v1/method.py", line 154, in __call__
return wrapped_func(*args, **kwargs)
TypeError: __call__() got an unexpected keyword argument 'metadata'
Scenario 2 - when metadata = None: Getting error message TypeError: 'NoneType' object is not iterable
PubSubHook().acknowledge(subscription=SNOW_SUBSCRIPTION,project_id=PROJECT_ID, ack_ids=ack_id_list, retry=Retry , timeout=10,metadata=None)
File "/opt/python3.8/lib/python3.8/site-packages/airflow/providers/google/cloud/operators/pubsub.py", line 785, in execute
ret = handle_messages(pulled_messages, context)
File "/home/airflow/gcs/dags/snow_ticket_creator_1.py", line 70, in print_messages
PubSubHook().acknowledge(subscription=SNOW_SUBSCRIPTION,project_id=PROJECT_ID, ack_ids=ack_id_list, retry=Retry , timeout=10,metadata=None)
File "/opt/python3.8/lib/python3.8/site-packages/airflow/providers/google/common/hooks/base_google.py", line 457, in inner_wrapper
return func(self, *args, **kwargs)
File "/opt/python3.8/lib/python3.8/site-packages/airflow/providers/google/cloud/hooks/pubsub.py", line 561, in acknowledge
subscriber.acknowledge(
File "/opt/python3.8/lib/python3.8/site-packages/google/pubsub_v1/services/subscriber/client.py", line 1263, in acknowledge
metadata = tuple(metadata) + (
TypeError: 'NoneType' object is not iterable
**Scenario 3 - when metadata is omitted: Getting error -> call() got an unexpected keyword argument 'metadata'
PubSubHook().acknowledge(subscription=SNOW_SUBSCRIPTION,project_id=PROJECT_ID, ack_ids=ack_id_list, retry=Retry , timeout=10)
Traceback: Same as Scenario 1
Composer Version composer-1.19.12
Airflow Version -airflow-2.3.3
Complete Code:
from __future__ import annotations
import os
from datetime import datetime
import base64
import airflow
from airflow import DAG
import json
from airflow.operators.bash import BashOperator
from airflow.providers.google.cloud.operators.pubsub import (
PubSubCreateSubscriptionOperator,
PubSubPullOperator,
)
from airflow.providers.google.cloud.sensors.pubsub import PubSubPullSensor
from airflow.providers.google.cloud.hooks.pubsub import PubSubHook,Retry
from airflow.utils.trigger_rule import TriggerRule
ENV_ID = "Dev" #os.environ.get("SYSTEM_TESTS_ENV_ID")
PROJECT_ID = "abcdef" #os.environ.get("SYSTEM_TESTS_GCP_PROJECT", "your-project-id")
DAG_ID = "DataPullDag_1"
TOPIC_ID = "alert_topic_jp" #f"topic-{DAG_ID}-{ENV_ID}"
SNOW_SUBSCRIPTION="alert_subscription_jp"
def print_ack_messages(pulled_messages, context):
for idx,m in enumerate(pulled_messages):
data = m.message.data.decode('utf-8')
print(f'################----------{data}')
data_json_dict = json.loads(data)
print(f"AckID: { m.ack_id }, incident_id: { data_json_dict['incident']['incident_id'] }"
f"scoping_project_id: { data_json_dict['incident']['scoping_project_id'] } "
f"resource_name: { data_json_dict['incident']['resource_name'] } "
f"summary: { data_json_dict['incident']['summary'] } ")
#acknowldege message
ack_id_list = [m.ack_id]
print(type(ack_id_list))
if idx == 0:
PubSubHook().acknowledge(subscription=SNOW_SUBSCRIPTION,project_id=PROJECT_ID, ack_ids=ack_id_list, retry=Retry , timeout=10)
print(f"Successfully acknowldeged incident_id: { data_json_dict['incident']['incident_id'] }")
with DAG(
DAG_ID,
schedule_interval='#once', # Override to match your needs
start_date=airflow.utils.dates.days_ago(0),
catchup=False,
) as dag:
# [START howto_operator_gcp_pubsub_create_subscription]
subscribe_task = PubSubCreateSubscriptionOperator(
task_id="subscribe_task", project_id=PROJECT_ID, topic=TOPIC_ID,subscription=SNOW_SUBSCRIPTION
)
subscription = subscribe_task.output
pull_messages_operator = PubSubPullOperator(
task_id="pull_messages_operator",
ack_messages=False,
project_id=PROJECT_ID,
messages_callback=print_ack_messages,
subscription=subscription,
max_messages=50,
)
(
subscribe_task
>> pull_messages_operator
)
I did bit more experimenting into the actual source code for PullOperator (if we provide "ack_messages=True" in the PullOperator itself, it will acknowledge all the pulled messages by calling hook.acknowledge(project_id=self.project_id,subscription=self.subscription,messages=pulled_messages,) ) and found out that the retry object in my acknowledge call was creating the issue. So instead of PubSubHook().acknowledge(subscription=SNOW_SUBSCRIPTION,project_id=PROJECT_ID, ack_ids=ack_id_list, retry=Retry , timeout=10) i have dropped retry object and used PubSubHook().acknowledge(subscription=SNOW_SUBSCRIPTION,project_id=PROJECT_ID, ack_ids=ack_id_list, timeout=10) and it worked!!!.
However as per the documentation documentation, retry object has a purpose,
retry object used to retry requests. If None is specified, requests will not be retried.
Update 31/10/2022
This was due to a mistake in the code, instead of Retry object i was using Retry class. Thank you for pointing this out Taragolis (airflow collaborator).
In the above code if we replace Retry class with retry object it will work, as shown below
retryObj= Retry(initial=10, maximum=10, multiplier=1.0, deadline=600)
PubSubHook().acknowledge(subscription=SNOW_SUBSCRIPTION,project_id=PROJECT_ID, ack_ids=ack_id_list, retry=retryObj, timeout=10)

Unit test for exception raised in custom GNU radio python block

I have created a custom python sync block for use in a gnuradio flowgraph. The block tests for invalid input and, if found, raises a ValueError exception. I would like to create a unit test to verify that the exception is raised when the block indeed receives invalid input data.
As part of the python-based qa test for this block, I created a flowgraph such that the block receives invalid data. When I run the test, the block does appear to raise the exception but then hangs.
What is the appropriate way to test for this? Here is a minimal working example:
#!/usr/bin/env python
import numpy as np
from gnuradio import gr, gr_unittest, blocks
class validate_input(gr.sync_block):
def __init__(self):
gr.sync_block.__init__(self,
name="validate_input",
in_sig=[np.float32],
out_sig=[np.float32])
self.max_input = 100
def work(self, input_items, output_items):
in0 = input_items[0]
if (np.max(in0) > self.max_input):
raise ValueError('input exceeds max.')
validated_in = output_items[0]
validated_in[:] = in0
return len(output_items[0])
class qa_validate_input (gr_unittest.TestCase):
def setUp (self):
self.tb = gr.top_block ()
def tearDown (self):
self.tb = None
def test_check_valid_data(self):
src_data = (0, 201, 92)
src = blocks.vector_source_f(src_data)
validate = validate_input()
snk = blocks.vector_sink_f()
self.tb.connect (src, validate)
self.tb.connect (validate, snk)
self.assertRaises(ValueError, self.tb.run)
if __name__ == '__main__':
gr_unittest.run(qa_validate_input, "qa_validate_input.xml")
which produces:
DEPRECATED: Using filename with gr_unittest does no longer have any effect.
handler caught exception: input exceeds max.
Traceback (most recent call last):
File "/home/xxx/devel/gnuradio3_8/lib/python3.6/dist-packages/gnuradio/gr/gateway.py", line 60, in eval
try: self._callback()
File "/home/xxx/devel/gnuradio3_8/lib/python3.6/dist-packages/gnuradio/gr/gateway.py", line 230, in __gr_block_handle
) for i in range(noutputs)],
File "qa_validate_input.py", line 21, in work
raise ValueError('input exceeds max.')
ValueError: input exceeds max.
thread[thread-per-block[1]: <block validate_input(2)>]: SWIG director method error. Error detected when calling 'feval_ll.eval'
^CF
======================================================================
FAIL: test_check_valid_data (__main__.qa_validate_input)
----------------------------------------------------------------------
Traceback (most recent call last):
File "qa_validate_input.py", line 47, in test_check_valid_data
self.assertRaises(ValueError, self.tb.run)
AssertionError: ValueError not raised by run
----------------------------------------------------------------------
Ran 1 test in 1.634s
FAILED (failures=1)
The top_block's run() function does not call the block's work() function directly but starts the internal task scheduler and its threads and waits them to finish.
One way to unit test the error handling in your block is to call the work() function directly
def test_check_valid_data(self):
src_data = [[0, 201, 92]]
output_items = [[]]
validate = validate_input()
self.assertRaises(ValueError, lambda: validate.work(src_data, output_items))

async with" if the event loop is running

I'm writing my first telegram bot with telepot and telethon
my main code is:
import sys
import asyncio
import random
import telepot
import telepot.aio
from telepot.aio.loop import MessageLoop
from telepot.namedtuple import ReplyKeyboardMarkup, KeyboardButton, ReplyKeyboardRemove, ForceReply
from telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton
from telepot.namedtuple import InlineQueryResultArticle, InlineQueryResultPhoto, InputTextMessageContent
async def on_chat_message(msg):
global listenFromKeyboardUsername, listenFromKeyboardPassword, listenFromKeyboardLinkGroup
content_type, chat_type, chat_id = telepot.glance(msg)
chat_id = str(chat_id)
if content_type == 'text':
name = msg["from"]["first_name"]
txt = msg['text']
# stuff..
elif userExistsInDb and userData['listenFromKeyboardLinkGroup'] and chat_id == doc.id:
group = telegramGetMessages.checkGroup(txt)
print(group)
TOKEN = "*******"
bot = telepot.aio.Bot(TOKEN)
answerer = telepot.aio.helper.Answerer(bot)
loop = asyncio.get_event_loop()
loop.create_task(MessageLoop(bot, {'chat': on_chat_message,
'callback_query': on_callback_query}).run_forever())
print('Listening ...')
loop.run_forever()
from the code above I call the checkGroup function:
def checkGroup(hash):
initClient()
global result
hash = hash.replace('https://t.me/joinchat/', '')
with TelegramClient(name, api_id, api_hash) as client:
result = client(functions.messages.CheckChatInviteRequest(hash=hash))
if isinstance(result, ChatInvite):
print('You are not inside the group')
with TelegramClient(name, api_id, api_hash) as client:
client(functions.messages.ImportChatInviteRequest(hash=hash))
result = client(functions.messages.CheckChatInviteRequest(hash=hash))
return result
where I'm getting this error:
RuntimeError: You must use "async with" if the event loop is running (i.e. you are inside an "async def")
then I edit the checkGroup function with async def checkGroup(hash): ..
but now I'm geting this error and I don't know what to do:
Task exception was never retrieved
future: <Task finished coro=<Router.route() done, defined at /home/ale/PycharmProjects/newTelegramBot/venv/lib/python3.6/site-packages/telepot/aio/helper.py:213> exception=NotFound('No document to update: projects/telegram-bot-4ee9f/databases/(default)/documents/users/585089661/data/groups',)>
Traceback (most recent call last):
File "/home/ale/PycharmProjects/newTelegramBot/venv/lib/python3.6/site-packages/google/api_core/grpc_helpers.py", line 57, in error_remapped_callable
return callable_(*args, **kwargs)
File "/home/ale/PycharmProjects/newTelegramBot/venv/lib/python3.6/site-packages/grpc/_channel.py", line 549, in __call__
return _end_unary_response_blocking(state, call, False, None)
File "/home/ale/PycharmProjects/newTelegramBot/venv/lib/python3.6/site-packages/grpc/_channel.py", line 466, in _end_unary_response_blocking
raise _Rendezvous(state, None, None, deadline)
grpc._channel._Rendezvous: <_Rendezvous of RPC that terminated with:
status = StatusCode.NOT_FOUND
details = "No document to update: projects/telegram-bot-4ee9f/databases/(default)/documents/users/585089661/data/groups"
debug_error_string = "{"created":"#1552727386.760400590","description":"Error received from peer","file":"src/core/lib/surface/call.cc","file_line":1039,"grpc_message":"No document to update: projects/telegram-bot-4ee9f/databases/(default)/documents/users/585089661/data/groups","grpc_status":5}"
>
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/ale/PycharmProjects/newTelegramBot/venv/lib/python3.6/site-packages/telepot/aio/helper.py", line 244, in route
return await _invoke(fn, msg, *args, **kwargs)
File "/home/ale/PycharmProjects/newTelegramBot/venv/lib/python3.6/site-packages/telepot/aio/helper.py", line 16, in _invoke
return await fn(*args, **kwargs)
File "/home/ale/PycharmProjects/newTelegramBot/chatAsync.py", line 119, in on_chat_message
database.updateUserData(chat_id, 'groups', 'nameGroup', txt)
File "/home/ale/PycharmProjects/newTelegramBot/database.py", line 38, in updateUserData
field: key,
File "/home/ale/PycharmProjects/newTelegramBot/venv/lib/python3.6/site-packages/google/cloud/firestore_v1beta1/document.py", line 371, in update
write_results = batch.commit()
File "/home/ale/PycharmProjects/newTelegramBot/venv/lib/python3.6/site-packages/google/cloud/firestore_v1beta1/batch.py", line 148, in commit
metadata=self._client._rpc_metadata,
File "/home/ale/PycharmProjects/newTelegramBot/venv/lib/python3.6/site-packages/google/cloud/firestore_v1beta1/gapic/firestore_client.py", line 946, in commit
request, retry=retry, timeout=timeout, metadata=metadata
File "/home/ale/PycharmProjects/newTelegramBot/venv/lib/python3.6/site-packages/google/api_core/gapic_v1/method.py", line 143, in __call__
return wrapped_func(*args, **kwargs)
File "/home/ale/PycharmProjects/newTelegramBot/venv/lib/python3.6/site-packages/google/api_core/retry.py", line 270, in retry_wrapped_func
on_error=on_error,
File "/home/ale/PycharmProjects/newTelegramBot/venv/lib/python3.6/site-packages/google/api_core/retry.py", line 179, in retry_target
return target()
File "/home/ale/PycharmProjects/newTelegramBot/venv/lib/python3.6/site-packages/google/api_core/timeout.py", line 214, in func_with_timeout
return func(*args, **kwargs)
File "/home/ale/PycharmProjects/newTelegramBot/venv/lib/python3.6/site-packages/google/api_core/grpc_helpers.py", line 59, in error_remapped_callable
six.raise_from(exceptions.from_grpc_error(exc), exc)
File "<string>", line 3, in raise_from
google.api_core.exceptions.NotFound: 404 No document to update: projects/telegram-bot-4ee9f/databases/(default)/documents/users/585089661/data/groups
/usr/lib/python3.6/asyncio/base_events.py:1441: RuntimeWarning: coroutine 'checkGroup' was never awaited
handle = None # Needed to break cycles when an exception occurs.
I'm reading around, and maybe for this problem it's better to use the delegatoBot, but I'm not really sure because I can't find great examples!
It wold be wonderfull recive a reply, If you need anything just ask!
Thankyou

pydev unresolved import, but code runs on Idle

I'm trying to write a simple GUI for a graphing program I am writing, it runs in Idle(Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32) with no problems, but when I try to run in Eclipse, pydev, the script doesn't work.
I opened the console in eclipse and tried to import FigureCanvas(the only error eclipse is showing me) and I got this is the error message I get:
from matplotlib.backends.backend_qt5agg import FigureCanvas
Backend TkAgg is interactive backend. Turning interactive mode on.
Traceback (most recent call last):
File "C:\Users\Daniel\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\backends\qt_compat.py", line 198, in <module>
from PySide import QtCore, QtGui, __version__, __version_info__
File "C:\Users\Daniel\.p2\pool\plugins\org.python.pydev.core_7.1.0.201902031515\pysrc\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
module = self._system_import(name, *args, **kwargs)
ModuleNotFoundError: No module named 'PySide'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "C:\Users\Daniel\.p2\pool\plugins\org.python.pydev.core_7.1.0.201902031515\pysrc\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
module = self._system_import(name, *args, **kwargs)
File "C:\Users\Daniel\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\backends\backend_qt5agg.py", line 16, in <module>
from .backend_qt5 import (
File "C:\Users\Daniel\.p2\pool\plugins\org.python.pydev.core_7.1.0.201902031515\pysrc\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
module = self._system_import(name, *args, **kwargs)
File "C:\Users\Daniel\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\backends\backend_qt5.py", line 18, in <module>
import matplotlib.backends.qt_editor.figureoptions as figureoptions
File "C:\Users\Daniel\.p2\pool\plugins\org.python.pydev.core_7.1.0.201902031515\pysrc\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
module = self._system_import(name, *args, **kwargs)
File "C:\Users\Daniel\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\backends\qt_editor\figureoptions.py", line 20, in <module>
import matplotlib.backends.qt_editor.formlayout as formlayout
File "C:\Users\Daniel\.p2\pool\plugins\org.python.pydev.core_7.1.0.201902031515\pysrc\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
module = self._system_import(name, *args, **kwargs)
File "C:\Users\Daniel\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\backends\qt_editor\formlayout.py", line 56, in <module>
from matplotlib.backends.qt_compat import QtGui, QtWidgets, QtCore
File "C:\Users\Daniel\.p2\pool\plugins\org.python.pydev.core_7.1.0.201902031515\pysrc\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
module = self._system_import(name, *args, **kwargs)
File "C:\Users\Daniel\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\backends\qt_compat.py", line 201, in <module>
"Matplotlib qt-based backends require an external PyQt4, PyQt5,\n"
ImportError: Matplotlib qt-based backends require an external PyQt4, PyQt5,
PySide or PySide2 package to be installed, but it was not found.
this is the part of the code that is being run, both on idle(which works) and on eclipse(doesn't work)
# mplwidget.py
from PyQt5.QtWidgets import*
from matplotlib.backends.backend_qt5agg import FigureCanvas
from matplotlib.figure import Figure
class MplWidget(QWidget):
def __init__(self, parent = None):
QWidget.__init__(self, parent)
self.canvas = FigureCanvas(Figure())
vertical_layout = QVBoxLayout()
vertical_layout.addWidget(self.canvas)
self.canvas.axes = self.canvas.figure.add_subplot(111)
self.setLayout(vertical_layout)
this is the main function that calles the mpwidget
# ------------------------------------------------------
# ---------------------- main.py -----------------------
# ------------------------------------------------------
from PyQt5.QtWidgets import*
from PyQt5.uic import loadUi
from matplotlib.backends.backend_qt5agg import (NavigationToolbar2QT as NavigationToolbar)
import numpy as np
import random
class MatplotlibWidget(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
loadUi("UI.ui",self)
self.setWindowTitle("PyQt5 & Matplotlib Example GUI")
#self.pushButton_generate_random_signal.clicked.connect(self.update_graph)
self.addToolBar(NavigationToolbar(self.MplWidget.canvas, self))
def update_graph(self):
fs = 500
f = random.randint(1, 100)
ts = 1/fs
length_of_signal = 100
t = np.linspace(0,1,length_of_signal)
cosinus_signal = np.cos(2*np.pi*f*t)
sinus_signal = np.sin(2*np.pi*f*t)
self.MplWidget.canvas.axes.clear()
self.MplWidget.canvas.axes.plot(t, cosinus_signal)
self.MplWidget.canvas.axes.plot(t, sinus_signal)
self.MplWidget.canvas.axes.legend(('cosinus', 'sinus'),loc='upper right')
self.MplWidget.canvas.axes.set_title('Cosinus - Sinus Signal')
self.MplWidget.canvas.draw()
app = QApplication([])
window = MatplotlibWidget()
window.show()
app.exec_()
when I try to run the code in eclipse nothing happens, but whe it runs on idle every thing opens the way I expect
This usually means that some environment variable is not configured the same way in both environments.
Please take a look at the FAQ: http://www.pydev.org/faq.html#MyProgramDoesNotWorkInPyDev to see how to proceed (mainly print the environment/PYTHONPATH on both to check the differences and fix the config on PyDev).

Resources