Handle internet exception on python script startup - python

I want a python script to execute on startup, so for that, I created a bat file and a vbs file
and it works when there is internet but most of the time when I turn on the pc and log in, the script launches before the pc connects to the internet and it gives me this error:
Traceback (most recent call last):
File "D:\Python-projects\Personal_assistant\.venv\lib\site-packages\urllib3\connection.py", line 174, in _new_conn
conn = connection.create_connection(
File "D:\Python-projects\Personal_assistant\.venv\lib\site-packages\urllib3\util\connection.py", line 72, in create_connection
for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
File "C:\Users\ACERq\AppData\Local\Programs\Python\Python39\lib\socket.py", line 953, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11001] getaddrinfo failed
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:\Python-projects\Personal_assistant\.venv\lib\site-packages\urllib3\connectionpool.py", line 703, in urlopen
httplib_response = self._make_request(
File "D:\Python-projects\Personal_assistant\.venv\lib\site-packages\urllib3\connectionpool.py", line 386, in _make_request
self._validate_conn(conn)
File "D:\Python-projects\Personal_assistant\.venv\lib\site-packages\urllib3\connectionpool.py", line 1040, in _validate_conn
conn.connect()
File "D:\Python-projects\Personal_assistant\.venv\lib\site-packages\urllib3\connection.py", line 358, in connect
conn = self._new_conn()
File "D:\Python-projects\Personal_assistant\.venv\lib\site-packages\urllib3\connection.py", line 186, in _new_conn
raise NewConnectionError(
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPSConnection object at 0x0000020F127D5FD0>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed
Traceback (most recent call last):
File "d:\Python-projects\Personal_assistant\Friday.py", line 5, in <module>
import pywhatkit as kit
File "D:\Python-projects\Personal_assistant\.venv\lib\site-packages\pywhatkit\__init__.py", line 16, in <module>
from pywhatkit.whats import (
File "D:\Python-projects\Personal_assistant\.venv\lib\site-packages\pywhatkit\whats.py", line 13, in <module>
core.check_connection()
File "D:\Python-projects\Personal_assistant\.venv\lib\site-packages\pywhatkit\core\core.py", line 41, in check_connection
raise InternetException(pywhatkit.core.exceptions.InternetException: Error while connecting to the Internet. Make sure you are connected to the Internet!
I am also using a virtual environment for the dependencies. Is there any way I can handle these exceptions or any way to execute a python script only after getting connected to the internet. Any help would be appreciated!
.bat file
#echo off
python D:\Python-projects\Personal_assistant\Friday.py
#pause
.vbs file
CreateObject("Wscript.Shell").Run "D:\Python-projects\Personal_assistant\Friday.bat", 0 , True

:wait
timeout /t 1 >nul
ping -n 1 google.com|find "TTL">nul
if errorlevel 1 goto wait
Should ping google.com every second until a response is received containing TTL

Related

Problems with pythonanywhere [duplicate]

I made a Discord Bot using Python 3.6. It runs and behaves perfectly when run on my computer, yet when I run it on PythonAnywhere, I get this message. I installed Discord.py and all necessary modules. Please help. I am not that very good with complex programming talk, and not at all good with web talk, so please answer as simply as you can. Does this issue only happen with PythonAnywhere or all remote hosting sites?
01:42 ~ $ python3.6 MyCoolBot.py
Traceback (most recent call last):
File "/home/CompuGenius/.local/lib/python3.6/site-packages/aiohttp/connector.py", line 601, in _create_direc
t_connection
local_addr=self._local_addr)
File "/usr/lib/python3.6/asyncio/base_events.py", line 778, in create_connection
raise exceptions[0]
File "/usr/lib/python3.6/asyncio/base_events.py", line 765, in create_connection
yield from self.sock_connect(sock, address)
File "/usr/lib/python3.6/asyncio/selector_events.py", line 450, in sock_connect
return (yield from fut)
File "/usr/lib/python3.6/asyncio/selector_events.py", line 480, in _sock_connect_cb
raise OSError(err, 'Connect call failed %s' % (address,))
ConnectionRefusedError: [Errno 111] Connect call failed ('104.16.58.5', 443)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/CompuGenius/.local/lib/python3.6/site-packages/aiohttp/connector.py", line 304, in connect
yield from self._create_connection(req)
File "/home/CompuGenius/.local/lib/python3.6/site-packages/aiohttp/connector.py", line 578, in _create_conne
ction
transport, proto = yield from self._create_direct_connection(req)
File "/home/CompuGenius/.local/lib/python3.6/site-packages/aiohttp/connector.py", line 624, in _create_direc
t_connection
(req.host, req.port, exc.strerror)) from exc
aiohttp.errors.ClientOSError: [Errno 111] Can not connect to discordapp.com:443 [Connect call failed ('104.16.
58.5', 443)]
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "MyCoolBot.py", line 39, in <module>
client.run('MY_BOT_TOKEN')
File "/home/CompuGenius/.local/lib/python3.6/site-packages/discord/client.py", line 519, in run
self.loop.run_until_complete(self.start(*args, **kwargs))
File "/usr/lib/python3.6/asyncio/base_events.py", line 468, in run_until_complete
return future.result()
File "/home/CompuGenius/.local/lib/python3.6/site-packages/discord/client.py", line 490, in start
yield from self.login(*args, **kwargs)
File "/home/CompuGenius/.local/lib/python3.6/site-packages/discord/client.py", line 416, in login
yield from getattr(self, '_login_' + str(n))(*args, **kwargs)
File "/home/CompuGenius/.local/lib/python3.6/site-packages/discord/client.py", line 346, in _login_1
data = yield from self.http.static_login(token, bot=is_bot)
File "/home/CompuGenius/.local/lib/python3.6/site-packages/discord/http.py", line 258, in static_login
data = yield from self.request(Route('GET', '/users/#me'))
File "/home/CompuGenius/.local/lib/python3.6/site-packages/discord/http.py", line 137, in request
r = yield from self.session.request(method, url, **kwargs)
File "/home/CompuGenius/.local/lib/python3.6/site-packages/aiohttp/client.py", line 555, in __iter__
resp = yield from self._coro
File "/home/CompuGenius/.local/lib/python3.6/site-packages/aiohttp/client.py", line 198, in _request
conn = yield from self._connector.connect(req)
File "/home/CompuGenius/.local/lib/python3.6/site-packages/aiohttp/connector.py", line 314, in connect
.format(key, exc.strerror)) from exc
aiohttp.errors.ClientOSError: [Errno 111] Cannot connect to host discordapp.com:443 ssl:True [Can not connect to discordapp.com:443 [Connect call failed ('104.16.58.5', 443)]]
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x7f4b25d81be0>
This is because PythonAnywhere requires a proxy in such a way that the aiohttp websockets don't support. There's a thread on their forums about it here: https://www.pythonanywhere.com/forums/topic/7384/ (See #Patrick Haugh's comment above)

Celery send task to rabbitmq [Errno 111] Connection refused

I'am trying to send task from django local app too remote rabbitmq server (preprod through vpn) but when I'm trying to send it always same error occure. Two errors code are related [Errno -9] Address family for hostname not supported and [Errno 111] Connection refused. The port 5672 is open the user is not the default user and the broker url is amqp://dist:dist#amqp.nopow-link.com:5672.
If someone can help me to understand what I'm doing wrong.
From the client:
>>> task.hello_task.apply_async()
Traceback (most recent call last):
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/kombu/utils/functional.py", line 30, in __call__
return self.__value__
AttributeError: 'ChannelPromise' object has no attribute '__value__'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/amqp/transport.py", line 173, in _connect
host, port, family, socket.SOCK_STREAM, SOL_TCP)
File "/usr/lib/python3.7/socket.py", line 748, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -9] Address family for hostname not supported
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/kombu/connection.py", line 447, in _reraise_as_library_errors
yield
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/kombu/connection.py", line 438, in _ensure_connection
callback, timeout=timeout
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/kombu/utils/functional.py", line 312, in retry_over_time
return fun(*args, **kwargs)
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/kombu/connection.py", line 878, in _connection_factory
self._connection = self._establish_connection()
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/kombu/connection.py", line 813, in _establish_connection
conn = self.transport.establish_connection()
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/kombu/transport/pyamqp.py", line 201, in establish_connection
conn.connect()
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/amqp/connection.py", line 323, in connect
self.transport.connect()
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/amqp/transport.py", line 113, in connect
self._connect(self.host, self.port, self.connect_timeout)
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/amqp/transport.py", line 184, in _connect
"failed to resolve broker hostname"))
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/amqp/transport.py", line 197, in _connect
self.sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/celery/app/task.py", line 579, in apply_async
**options
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/celery/app/base.py", line 788, in send_task
amqp.send_task_message(P, name, message, **options)
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/celery/app/amqp.py", line 519, in send_task_message
**properties
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/kombu/messaging.py", line 180, in publish
exchange_name, declare, timeout
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/kombu/connection.py", line 524, in _ensured
return fun(*args, **kwargs)
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/kombu/messaging.py", line 186, in _publish
channel = self.channel
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/kombu/messaging.py", line 209, in _get_channel
channel = self._channel = channel()
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/kombu/utils/functional.py", line 32, in __call__
value = self.__value__ = self.__contract__()
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/kombu/messaging.py", line 225, in <lambda>
channel = ChannelPromise(lambda: connection.default_channel)
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/kombu/connection.py", line 896, in default_channel
self._ensure_connection(**conn_opts)
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/kombu/connection.py", line 438, in _ensure_connection
callback, timeout=timeout
File "/usr/lib/python3.7/contextlib.py", line 130, in __exit__
self.gen.throw(type, value, traceback)
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/kombu/connection.py", line 451, in _reraise_as_library_errors
raise ConnectionError(str(exc)) from exc
kombu.exceptions.OperationalError: [Errno 111] Connection refused
On the server:
user
Listing permissions for user "dist" ...
/ .* .* .*
port
tcp 0 0 0.0.0.0:5672 0.0.0.0:* LISTEN 115995/beam.smp
On server nothing append when listening with tcpdump on port 5672 and no logs are displayed too (log.file.level = debug)
Notice: If I'am sending the same task from the server it's working well.
[2022-05-04 13:24:12,678: INFO/MainProcess] Task core.task.hello_task[a34f9869-03b8-4f4b-8139-b56f90deb469] received
[2022-05-04 13:24:12,680: WARNING/ForkPoolWorker-1] You want me to say hello?
[2022-05-04 13:24:12,680: WARNING/ForkPoolWorker-1] Hello.
[2022-05-04 13:24:12,680: INFO/ForkPoolWorker-1] Task core.task.hello_task[a34f9869-03b8-4f4b-8139-b56f90deb469] succeeded in 0.0006248119752854109s: None

Error When Running my Discord Bot on Python Anywhere

I made a Discord Bot using Python 3.6. It runs and behaves perfectly when run on my computer, yet when I run it on PythonAnywhere, I get this message. I installed Discord.py and all necessary modules. Please help. I am not that very good with complex programming talk, and not at all good with web talk, so please answer as simply as you can. Does this issue only happen with PythonAnywhere or all remote hosting sites?
01:42 ~ $ python3.6 MyCoolBot.py
Traceback (most recent call last):
File "/home/CompuGenius/.local/lib/python3.6/site-packages/aiohttp/connector.py", line 601, in _create_direc
t_connection
local_addr=self._local_addr)
File "/usr/lib/python3.6/asyncio/base_events.py", line 778, in create_connection
raise exceptions[0]
File "/usr/lib/python3.6/asyncio/base_events.py", line 765, in create_connection
yield from self.sock_connect(sock, address)
File "/usr/lib/python3.6/asyncio/selector_events.py", line 450, in sock_connect
return (yield from fut)
File "/usr/lib/python3.6/asyncio/selector_events.py", line 480, in _sock_connect_cb
raise OSError(err, 'Connect call failed %s' % (address,))
ConnectionRefusedError: [Errno 111] Connect call failed ('104.16.58.5', 443)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/CompuGenius/.local/lib/python3.6/site-packages/aiohttp/connector.py", line 304, in connect
yield from self._create_connection(req)
File "/home/CompuGenius/.local/lib/python3.6/site-packages/aiohttp/connector.py", line 578, in _create_conne
ction
transport, proto = yield from self._create_direct_connection(req)
File "/home/CompuGenius/.local/lib/python3.6/site-packages/aiohttp/connector.py", line 624, in _create_direc
t_connection
(req.host, req.port, exc.strerror)) from exc
aiohttp.errors.ClientOSError: [Errno 111] Can not connect to discordapp.com:443 [Connect call failed ('104.16.
58.5', 443)]
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "MyCoolBot.py", line 39, in <module>
client.run('MY_BOT_TOKEN')
File "/home/CompuGenius/.local/lib/python3.6/site-packages/discord/client.py", line 519, in run
self.loop.run_until_complete(self.start(*args, **kwargs))
File "/usr/lib/python3.6/asyncio/base_events.py", line 468, in run_until_complete
return future.result()
File "/home/CompuGenius/.local/lib/python3.6/site-packages/discord/client.py", line 490, in start
yield from self.login(*args, **kwargs)
File "/home/CompuGenius/.local/lib/python3.6/site-packages/discord/client.py", line 416, in login
yield from getattr(self, '_login_' + str(n))(*args, **kwargs)
File "/home/CompuGenius/.local/lib/python3.6/site-packages/discord/client.py", line 346, in _login_1
data = yield from self.http.static_login(token, bot=is_bot)
File "/home/CompuGenius/.local/lib/python3.6/site-packages/discord/http.py", line 258, in static_login
data = yield from self.request(Route('GET', '/users/#me'))
File "/home/CompuGenius/.local/lib/python3.6/site-packages/discord/http.py", line 137, in request
r = yield from self.session.request(method, url, **kwargs)
File "/home/CompuGenius/.local/lib/python3.6/site-packages/aiohttp/client.py", line 555, in __iter__
resp = yield from self._coro
File "/home/CompuGenius/.local/lib/python3.6/site-packages/aiohttp/client.py", line 198, in _request
conn = yield from self._connector.connect(req)
File "/home/CompuGenius/.local/lib/python3.6/site-packages/aiohttp/connector.py", line 314, in connect
.format(key, exc.strerror)) from exc
aiohttp.errors.ClientOSError: [Errno 111] Cannot connect to host discordapp.com:443 ssl:True [Can not connect to discordapp.com:443 [Connect call failed ('104.16.58.5', 443)]]
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x7f4b25d81be0>
This is because PythonAnywhere requires a proxy in such a way that the aiohttp websockets don't support. There's a thread on their forums about it here: https://www.pythonanywhere.com/forums/topic/7384/ (See #Patrick Haugh's comment above)

should I close each connection to the DB in rethinkDB?

I have a server built in python, using Tornado and RethinkDB. Its been running for a long time, opening several connections to the DB per user. I never had any major problems by leaving them open -never closing them-. But checking out the log file I found out there's a lot of this warnings:
File "/home/bundleroot/commentserver/app.py", line 30, in <module>
db_connection = r.connect(RDB_HOST,RDB_PORT)
File "/home/bundleroot/commentserver/env34/lib/python3.4/site-packages/rethinkdb/net.py", line 542, in connect
return conn.reconnect(timeout)
File "/home/bundleroot/commentserver/env34/lib/python3.4/site-packages/rethinkdb/net.py", line 475, in reconnect
return self._instance.connect(timeout)
File "/home/bundleroot/commentserver/env34/lib/python3.4/site-packages/rethinkdb/net.py", line 360, in connect
self._socket = SocketWrapper(self, timeout)
File "/home/bundleroot/commentserver/env34/lib/python3.4/site-packages/rethinkdb/net.py", line 268, in __init__
(self.host, self.port, ex))
rethinkdb.errors.RqlDriverError: Could not connect to localhost:28015. Error: [Errno 111] Connection refused
Traceback (most recent call last):
File "/home/bundleroot/commentserver/env34/lib/python3.4/site-packages/rethinkdb/net.py", line 244, in __init__
socket.create_connection((self.host, self.port), timeout)
File "/usr/lib/python3.4/socket.py", line 509, in create_connection
raise err
File "/usr/lib/python3.4/socket.py", line 500, in create_connection
sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused
Should I worry about it? In that case, what are the good practices?
Yes, you need to close the connection to avoid connection leaks. This Flask example, from RethinkDB, does it:
https://github.com/rethinkdb/rethinkdb-example-flask-backbone-todo/blob/master/todo.py#L47-L65
Even if RethinkDB does not enforce a hard limit on number of connections (I'm not sure if it does or not), you can run into the limits of the OS.

Redis Error 8 connecting localhost:6379. nodename nor servname provided, or not known

My environment is Mac OS 10.9.2, python3.3, redis-2.6.9 (64-bit).
I have many threads (nealy 2000) that use the same redis instance to write data, but some threads throw the following exceptions:
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.3/site-packages/redis/connection.py", line 250, in connect
sock = self._connect()
File "/usr/local/lib/python3.3/site-packages/redis/connection.py", line 268, in _connect
self.socket_timeout)
File "/usr/local/Cellar/python3/3.3.4/Frameworks/Python.framework/Versions/3.3/lib/python3.3/socket.py", line 417, in create_connecti
on
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
socket.gaierror: [Errno 8] nodename nor servname provided, or not known
Traceback (most recent call last):
File "/usr/local/Cellar/python3/3.3.4/Frameworks/Python.framework/Versions/3.3/lib/python3.3/threading.py", line 901, in _bootstrap_i
nner
self.run()
File "/usr/local/Cellar/python3/3.3.4/Frameworks/Python.framework/Versions/3.3/lib/python3.3/threading.py", line 858, in run
self._target(*self._args, **self._kwargs)
File "proxypool.py", line 289, in _efficiency_proxy
self.rdb.zadd(db_proxy, time_delay, proxy)
File "/usr/local/lib/python3.3/site-packages/redis/client.py", line 1345, in zadd
return self.execute_command('ZADD', name, *pieces)
File "/usr/local/lib/python3.3/site-packages/redis/client.py", line 464, in execute_command
connection.send_command(*args)
File "/usr/local/lib/python3.3/site-packages/redis/connection.py", line 334, in send_command
self.send_packed_command(self.pack_command(*args))
File "/usr/local/lib/python3.3/site-packages/redis/connection.py", line 316, in send_packed_command
self.connect()
File "/usr/local/lib/python3.3/site-packages/redis/connection.py", line 253, in connect
raise ConnectionError(self._error_message(e))
redis.exceptions.ConnectionError: Error 8 connecting localhost:6379. nodename nor servname provided, or not known.
Is there some way to solve this problem?
I tried to connect to redis server when this exception happens and use ulimit -n to set a larger number, but the two methods don't work.
I know why this happened. It's caused by the max number of connections to redis-server and it's related to the max number of file handlers that the OS sets.
If I set:
$ ulimit -n 1024
it works.
Most likely the reds server is not running. Run it using "redis-server" command.
brew services start redis (on mac)
I also faced this issue.
When you are using the wrong Redis HOST then you also meet that error.

Categories