名称错误:全局名称'sock'未定义。

4

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

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

错误

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

1
(1) Functions.py 的标题选择有些奇怪。(b) 你没有定义全局名称 sock。你显然知道 import 关键字,那为什么不使用它呢? - Marcin
1
@wim 打错字了 xD 我习惯打 .php - RobinJ
2个回答

7

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

嗯...这有点...有限。如果我每次都需要传递每个变量,那么代码很快就会变得混乱 :( 好吧,谢谢 :) - RobinJ
2
相反,如果您使用全局变量,那么代码将会很混乱。例如,如果您想要扩展程序以使用多个套接字,该怎么办?如果您确实需要全局变量,可以创建一个名为myGlobal的模块并在其中分配它。 - phihag

2
你的functions.py不知道sock是什么。尝试将sock实例作为参数传递。
def sendMessage (sock, receiver, message):
    sock.send ('PRIVMSG ' + ontvanger + ' :' + message + '\n')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接