NameError: global name 'sock' is not defined
14,724
Solution 1
There are no php-style module-overarching global variables in Python. Instead, let sendMessage
take the socket as an argument, like this:
# main.py
import socket
from functions import *
sock = socket.socket ()
sock.connect ((config['server']['host'], config['server']['poort']))
sendMessage (sock, receiver, config['nick'] + ' is here!')
# functions.py ; not .php
def sendMessage(sock, receiver, message):
sock.send ('PRIVMSG ' + ontvanger + ' :' + message + '\n')
Solution 2
Your functions.py
have no idea what sock
is. Try passing sock instance as an argument.
def sendMessage (sock, receiver, message):
sock.send ('PRIVMSG ' + ontvanger + ' :' + message + '\n')
Author by
RobinJ
Updated on June 04, 2022Comments
-
RobinJ over 1 year
I've defined a socket called sock in my Main.py. From Main.py I import Functions.py, where there's a function (or a method, dunno how they're called in Python) called sendMessage. In sendMessage I need to use the sock I defined in my Main.py. How do I do this? I've tried adding
global sock
to my function/method, but to no effect.Main.py
#! /usr/bin/env python import sys import socket import string import os import commands import time from config import * from functies import * from php import * sock = socket.socket () sock.connect ((config['server']['host'], config['server']['poort'])) ...
Functions.py
#! /usr/bin/env python def sendMessage (receiver, message): global sock sock.send ('PRIVMSG ' + ontvanger + ' :' + message + '\n')
The error
Traceback (most recent call last): File "Main.py", line 68, in <module> sendMessage (receiver, config['nick'] + ' is here!') File "/home/robin/microPy/Functions.py", line 4, in sendMessage sock.send ('PRIVMSG ' + receiver + ' :' + message + '\n') NameError: global name 'sock' is not defined