名称错误:未定义全局名称“sock”

2024-04-27 17:11:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Main.py中定义了一个名为sock的套接字。从Main.py导入function s.py,这里有一个名为sendMessage的函数(或者一个方法,不知道在Python中如何调用它们)。在sendMessage中,我需要使用Main.py中定义的sock。我该怎么做?我试过在函数/方法中添加global sock,但没有效果。

主.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']))

...

函数.py

#! /usr/bin/env python

def sendMessage (receiver, message):
    global sock
    sock.send ('PRIVMSG ' + ontvanger + ' :' + message + '\n')

错误

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

Tags: 方法函数frompyimportconfigmessage定义
2条回答

Python中没有php样式的模块覆盖全局变量。相反,让sendMessage将套接字作为参数,如下所示:

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

你的functions.py不知道sock是什么。尝试将sock实例作为参数传递。

def sendMessage (sock, receiver, message):
    sock.send ('PRIVMSG ' + ontvanger + ' :' + message + '\n')

相关问题 更多 >