python global name not defined_python - NameError: global name 'sock' is not defined

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

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 definedisualize that data onto a map. For this I am using Jinja2. However I am getting this error and I just don't understand why. Here is my code for that import webapp2from webapp2_extras import jinja2from webapp2_extras import jsonimport log

answer 1 >>---Accepted---Accepted---Accepted---

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')

ng something wrong with my variable or function scope. Whenever I try to pull out some of the functionality into separate functions it gives me the NameError: global name 'NAME' is not defined. I see that a lot of people are having a simila

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值