PyTorch multiprocessing error: ConnectionRefusedError: [Errno 111] Connection refused - multiprocessing

When I run the following code,
import torch.multiprocessing as mp
import torch
def f(q):
t = torch.ones([2,3])
q.put(t)
if __name__ == '__main__':
mp.set_start_method('spawn')
q = mp.Queue()
p1 = mp.Process(target=f, args=(q,))
p2 = mp.Process(target=f, args=(q,))
p1.start()
p2.start()
p1.join()
p2.join()
a = q.get()
b = q.get()
print(a, b)
I get the error:
ConnectionRefusedError: [Errno 111] Connection refused
It seems that this error is caused by torch.ones([2,3]). If in method f I put something else into q, such as a list or a value, it works fine. I've tried several approaches but none of them works for me. I really have no idea why this happens and how to deal with it. Any help would be much appreciated.

Related

sys:1: RuntimeWarning: coroutine 'AirthingsWaveDetect.get_sensors' was never awaited

I am a beginner trying to get the data from airthings plus to hubitat using a raspberry pi. When running a python script I get this error message :
readwaveplus.py:391: RuntimeWarning: coroutine 'AirthingsWaveDetect.get_sensor_data' was never awaited
data = airthingsdetect.get_sensor_data()[MAC]
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Read Error
^CTraceback (most recent call last):
File "readwaveplus.py", line 414, in <module>
time.sleep(SamplePeriod)
KeyboardInterrupt
sys:1: RuntimeWarning: coroutine 'AirthingsWaveDetect.get_sensors' was never awaited
It seems I need to add "await" somewhere but I am not able to figure out where. I tried to add await but not sure where It should be added.
Here is the script :
async def main():
logging.basicConfig()
_LOGGER.setLevel(logging.DEBUG)
ad = AirthingsWaveDetect(0)
num_dev_found = await ad.find_devices()
if num_dev_found > 0:
devices = await ad.get_info()
for mac, dev in devices.items():
_LOGGER.info("Device: {}: {}".format(mac, dev))
devices_sensors = await ad.get_sensors()
for mac, sensors in devices_sensors.items():
for sensor in sensors:
_LOGGER.info("Sensor: {}: {}".format(mac, sensor))
sensordata = await ad.get_sensor_data()
for mac, data in sensordata.items():
for name, val in data.items():
_LOGGER.info("Sensor data: {}: {}: {}".format(mac, name, val))
if __name__ == "__main__":
asyncio.run(main())
import time
import requests
# The period between two measurements in seconds (Default: 300)
SamplePeriod = 300
MAC = 'd8:71:4d:ca:de:dc'
# The hostname or IP address of the MQTT broker Hubitat hub to connect
makerAPIHostname = "192.168.1.38"
makerAPIAppID = "2416"
makerAPIToken = "8ca5e2ac-7d0b-4c24-a89b-f6022844e2ae"
makerAPIDeviceID = "AirThings Wave Plus"
from airthings import AirthingsWaveDetect
scan_interval = 120
airthingsdetect = AirthingsWaveDetect(scan_interval, MAC)
V_MAX = 3.0
V_MIN = 2.0
#---- Initialize ----#
URL = "http://{}/apps/api/{}/devices/{}/{}?access_token={}".format(makerAPIHostname, makerAPIAppID, makerAPIDeviceID, '{}/{}', makerAPIToken)
devices_sensors = airthingsdetect.get_sensors()
while True:
try:
data = airthingsdetect.get_sensor_data()[MAC]
except:
print( 'Read Error' )
pass
else:
sensorData = "{},{},{},{},{},{},{},{},{}".format(
data['temperature'],
data['humidity'],
data['rel_atm_pressure'],
data['co2'],
data['voc'],
round(data['radon_1day_avg']/37.,2),
round(data['radon_longterm_avg']/37.,2),
max(0, min(100, round( (data['battery']-V_MIN)/(V_MAX-V_MIN)*100))),
round(data['illuminance'])
)
#print( sensorData )
try:
request = URL.format('setValues', sensorData)
requests.get(request)
except:
pass
finally:
time.sleep(SamplePeriod)
Any idea ? Thanks.
Async needs an await but I don't know where. Thanks.

ESP32 crashes with Micropython with simple test program

Here is a simple Micropython program that I wrote to test my ESP32 Vroom32 board. It crashes after several minutes. I got about 38000 counts out of it.
from time import sleep
n = 0
while 1:
print(n)
n += 1
sleep(0.02)
Here is the code that I'm using to read it.
import serial, serial.tools.list_ports
import time
def find_port(): #Finds which port the arduino is plugged into
ports = list(serial.tools.list_ports.comports())
for p in ports:
if "EA60" in p[2]:
return(p[0])
usbport = find_port()
ser = serial.Serial(usbport, 115200) #setup serial
while 1:
try:
data = ser.readline()
ser.flushInput()
data = data.strip().decode()
print(data)
time.sleep(0.02)
except Exception as e:
print(e)
I've tried different things such as blinking the LED and slowing down the timing to 0.2 seconds. After doing those two things it ran about 8 hours and then crashed. When it crashed. I had to unplug the device and plug it back in and restart the python program on the computer before it would run again. Simply resetting the device did not work. Also, after I added the LED blink code (not included in the above example) the LED kept blinking the entire time. It was like it was still running, but not communicating.
New micropython code that blinks:
from time import sleep
from machine import Pin
n = 0
led = Pin(2, Pin.OUT)
while 1:
print(n)
n += 1
led.value(not led.value())
sleep(0.2)
Update:
Last night I added some code to try to catch the error. The board still crashed and no error file was created.
New main.py
from time import sleep
from machine import Pin
n = 0
led = Pin(2, Pin.OUT)
while 1:
try:
led.value(not led.value())
n += 1
print(n)
sleep(0.2)
except Exception as e:
print("ESP32: ", e)
New desktop script:
import serial, serial.tools.list_ports
import time
def find_port(): #Finds which port the arduino is plugged into
ports = list(serial.tools.list_ports.comports())
for p in ports:
if "EA60" in p[2]:
return(p[0])
usbport = find_port()
ser = serial.Serial(usbport, 115200, timeout=10) #setup serial
while 1:
try:
data = ser.readline()
ser.flushInput()
data = data.strip().decode()
print(data)
if "ESP32" in data:
with open("errors.txt", "a") as f:
err = data + "\n"
f.write(err)
time.sleep(0.2)
except Exception as e:
print(e)

How to interact with a running python script

As a start ive got a basic script which reads local unix syslog (/var/log/messages)
i want to build a tool which opens a socket (19999) locally and allows admin commands to be sent / processed.
As something i can build on basically i want to have the script on start up do the follow :
- open port 19999 locally
- start reading syslog storing "line" as the last line it has processed.
- when admin command of "printline" is seen print last known variable for "line"
Ive got basics done i think (script is below) where i have it open the relevant ports and it prints the commands sent to it from another client tool however it never starts to read the syslog.
#!/usr/bin/python
import socket
import subprocess
import sys
import time
from threading import Thread
MAX_LENGTH = 4096
def handle(clientsocket):
while 1:
buf = clientsocket.recv(MAX_LENGTH)
if buf == '': return #client terminated connection
print buf
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
PORT = 19999
HOST = '127.0.0.1'
serversocket.bind((HOST, PORT))
serversocket.listen(10)
while 1:
#accept connections from outside
(clientsocket, address) = serversocket.accept()
ct = Thread(target=handle, args=(clientsocket,))
ct.start()
def follow(thefile):
thefile.seek(0,2)
while True:
line = thefile.readline()
if not line:
time.sleep(0.1)
continue
yield line
if __name__ == '__main__':
logfile = open("/capture/log/uifitz/messages","r")
loglines = follow(logfile)
for line in loglines:
print line,
Any help would be appreciated. Python 2.6 by the way.

WinError 10038 an operaton was attempted on something that is not a socket

I'm trying to make chatting server in Python and I can't solve it. I'm running my code in CMD by using command python client.py localhost 9009.
this is the code that I am using:
#chat_client.py
import sys
import socket
import select
def chat_client():
if(len(sys.argv) < 3):
print("Usage: python chat_client.py hostname port")
sys.exit()
host = sys.argv[1]
port = int(sys.argv[2])
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
# connect to remote host
try:
s.connect((host, port))
except:
print("Unable to connect")
sys.exit()
print("Connected to remote host. You can start sending messages")
sys.stdout.write("[Me] "); sys.stdout.flush()
while 1:
socket_list = [sys.stdin, s]
# Get the list sockets which are readable
read_sockets, write_sockets, error_sockets = select.select(socket_list , [], [])
for sock in read_sockets:
if sock == s:
# incoming message from remote server, s
data = sock.recv(4096)
if not data:
print("\nDisconnected from chat server")
sys.exit()
else:
#print data
sys.stdout.write(data)
sys.stdout.write("[Me] "); sys.stdout.flush()
else:
# user entered a message
msg = sys.stdin.readline()
s.send(msg)
sys.stdout.write("[Me] "); sys.stdout.flush()
if __name__ == "__main__":
sys.exit(chat_client())
And this is the error that I'm getting:
I don't have a clue how to fix it. Help would be appreciated! :)
[Me] Traceback (most recent call last):
File "client.py", line 54, in <module>
sys.exit(chat_client())
File "client.py", line 32, in chat_client
read_sockets, write_sockets, error_sockets = select.select(socket_list , [],
[])

How do I create a script that does a continous ping?

The output initially is:
Reply from
Reply from
Reply from
Then I'll get, when the connection is lost:
Request timed out.
Request timed out.
Request timed out.
When it's reconnected the response is:
Reply from
Reply from
Reply from
Then I proceed to open a telnet session to my system and run python code.
When I use our utility I get this error below:
def fin():
tb_session.close_connection()
conftest.py:38:
import os
import subprocess
import re
bFlag = True
while bFlag == True:
a = subprocess.check_output('ping 127.0.0.1')
b = a.split('\n')
iReply = 0
for line in b:
print line
if re.search("Reply", line) == None:
pass
else:
iReply+=1
if iReply == 4:
print "Total replies are 4"
else:
print "Ping broken"
bFlag = False

Resources