I’ve noticed that after psychopy crashes (which happens a lot when using custom code blocks) I could not restart my experiment because the socket that the program uses to host the experiment on is in use. Every time this happened I would have to restart my computer for it to be fixed. I wrote a code to counteract this, all you have to do is put it somewhere in the ‘before experiment’ tab. It works dynamically between mac and windows. Feel free to use it if you are also stuck with this problem.
CODE:
Imports
import os
import sys
import platform
Port Kill functions
MACOS
def killport_mac(port):
result = os.popen(f"lsof -i :{port}“).read()
if result:
print(f"Port {port} is in use. Cleaning up…”)
pid_line = [line for line in result.split(‘\n’) if ‘python’ in line]
if pid_line:
pid = int(pid_line[0].split()[1]) # Extract the PID
os.system(f"kill -9 {pid}")
WINDOWS
def killport_windows(port):
result = os.popen(f’netstat -ano | findstr :{port}‘).read()
if result:
print(f"Port {port} is in use. Cleaning up…")
lines = result.split(’\n’)
parts = lines[0].split()
pid = int(parts[3])
os.system(f’taskkill /F /PID {pid}')
print(f"killed port {port} with PID {pid}")
else:
print(“No port in use, proceeding…”)
def killport(port):
os_type = platform.system()
if os_type == “Windows”:
print(“Windows OS detected”)
killport_windows(port)
elif os_type == “Darwin”:
print(“MacOS detected”)
killport_mac(port)
Check if port is in use and close it if so
port = 9036 # You might need to change this number, according to which port psychopy uses on your computer
killport(port)