Telethon on google colab pro plus - jupyter-notebook

I am trying to run telethon code on google colab plus and leave it running background. The code is running fine and has no errors while that is started and running in the browser tab. When I close the tab and reopened it, It showed too many repeated errors in the output console as below
RuntimeError: cannot enter context: <Context object at 0x7f0063bc04b0> is already entered
Exception in callback BaseAsyncIOLoop._handle_events(18, 1)
handle: <Handle BaseAsyncIOLoop._handle_events(18, 1)>
Traceback (most recent call last):
The code I am running on colab pro plus notebook
from telethon.sync import TelegramClient, events, Button
from telethon.sessions import StringSession
from telethon import functions, types
import asyncio
import nest_asyncio
nest_asyncio.apply()
api_id =
api_hash = ''
session=''
async def main():
async with TelegramClient(StringSession(session), api_id, api_hash) as client:
print("Inside")
#client.on(events.NewMessage(chats=[xxxxxxxxxx]))
async def my_event_handler(event):
print(event.raw_text)
while True:
#doSomething and wait for 0.03 seconds
await asyncio.sleep(0.03)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
I am unable to understand what caused the error because the errors are only showing up when I closed and reopened the notebook where the code is running

The issue got solved after installing this package
pip install --upgrade ipykernel
Source : https://github.com/jupyter/jupyter_console/issues/163#issuecomment-413468124

Related

Show log from sub python function in AirFlow

I'am facing with a little issue: I want to show all logs from all my python function opérateurs.
My Workflow:
my main python function is using in pythonoperateur (everything in this function were printed to the airflow logs)
my main python function calls other python functions but the print and logs in sub function not appear in airflow logs.
Even if I tried this:
import logging
logging.basicConfig(level=logging.DEBUG)
def subfunction():
logging.info('This is an info message') #not show in airflow log
def main_function():
print("call api") #it show in airflow log
subfunction()

How can I save VoD recordings without stopping streaming?

How can I stop recording intervally without stopping the stream to save the VoD in Ant Media Server in my stream sources and IP cameras?
You can achieve that with a python script. Assuming you have installed python3 and pip.
Following script stops and starts the recording again in user-defined intervals:
import sys
import sched, time
try:
import requests
print("requests library already installed!")
except ImportError:
try:
import pip
print("requests library is being installed")
pip.main(['install', '--user', 'requests'])
import requests
except ImportError:
print("pip is not installed, so it needs to be installed first to proceed further.\nYou can install pip with the following command:\nsudo apt install python3-pip")
slp=sched.scheduler(time.time,time.sleep)
def startStopRecording(s):
print("Stopping the recording of "+sys.argv[2])
response=requests.put(sys.argv[1]+"/rest/v2/broadcasts/"+sys.argv[2]+"/recording/false")
if response.json()["success"]:
print("recording of "+sys.argv[2]+" stopped successfully")
print(response.content)
print("starting the recording of "+sys.argv[2])
response=requests.put(sys.argv[1]+"/rest/v2/broadcasts/"+sys.argv[2]+"/recording/true")
print(response.content)
if response.json()["success"]:
print("recording of "+sys.argv[2]+" started successfully")
s.enter(int(sys.argv[3]),1,startStopRecording,(s,))
else:
print("Couldn't start the recording of "+sys.argv[2])
print("content of the response:\n"+response.content)
sys.exit()
else:
print("Couldn't stop the recording of "+sys.argv[2])
print("content of the response:")
print(response.content)
sys.exit()
slp.enter(int(sys.argv[3]),1,startStopRecording,(slp,))
slp.run()
Example usage would be like: python3 file.py https://domain/{Application} streamId interval
First parameter is the domain you are going to use like: https://someexample.com:5443/WebRTCAppEE
Second parameter is the stream id you want to use. Ex. stream123.
Third parameter is the duration of the interval you want to restart the recording. Duration unit is seconds. So 60 would be equal to 1 minute.

How to resolve: ImportError: cannot import name 'HttpNtlmAuth' in python3 script?

I have installed both requests and requests_ntlm modules using "sudo python3 -m pip install requests" (and requests_ntlm respectively) and both installs were successful.
When I then attempt to do "from requests import HttpNtlmAuth", I get an error stating "cannot import name 'HttpNtlmAuth'. I do not get this error on my "import requests" line.
When I do a "sudo python3 -m pip list", I see both are installed and are the latest versions.
I've not encountered this error before, only "cannot import module", so I'm unfamiliar with how to resolve this.
EDIT 1: Additional information. When I run this script from command line as "sudo", it works. Because I am running my python script from within a PHP file using "exec", I don't particularly want to run this as a root user. Is there a way around this, or possibly running the exec statement with sudo?
the HttpNtlmAuth class is in the requests_ntlm package so you'll need to have:
import requests
from requests_ntlm import HttpNtlmAuth
Then you'll be able to instantiate your authentication
session = requests.Session()
session.auth = HttpNtlmAuth('domain\\username','password')
session.get(url)

py2app: Compiles app but app has error on opening

I am working on a Python application in Python3.6 that I would like to convert into a standalone application that can be ported easily to other devices. I tried using py2app as in this tutorial.
Everything works well until I get to the point of actually creating the app. It does not throw any error in the creation process and creates the .app file, however, when I try to run it, A window pops up saying there is an error and gives me the options of terminating or opening the console. I tried opening the console but I cannot find any substantive information in the error messages.
These are the import statements that I have:
from urllib.request import urlopen, build_opener
from bs4 import BeautifulSoup, SoupStrainer
import ssl
import urllib
import sys
import subprocess
from tkinter import *
from tkinter.ttk import *
import webbrowser
from unidecode import unidecode
As far as I know the only 2 packages that aren't standard with python are bs4 and unidecode. My setup.py file looks like this:
from setuptools import setup
APP = ['GUImain.py']
DATA_FILES = ['logo.png']
OPTIONS = {'argv_emulation': True,
'iconfile': 'logo.png',
'includes': ['undidecode','bs4']}
setup(
app=APP,
data_files=DATA_FILES,
options={'py2app': OPTIONS},
setup_requires=['py2app'],
)
I haven't seen any other errors like this one from any of my searching. I have seen some suggestion that py2app doesn't fully support Python3.6. Does anyone know how I can figure out what error is being thrown? Any suggestions on different tools to use and tutorials on how to use them?

Disable the error message (failed to execute script) obtained with pyinstaller

Hi how do I disable the error (failed to execute script) when i run a exe process created with pyintaller ? without fix the script , because the script works well
"failed to execute script" says that your python program terminates with non-zero exit code by exception.
Try this:
import sys
def my_except_hook(exctype, value, traceback):
sys.exit(0)
return
sys.excepthook = my_except_hook

Resources