python - 名称错误 : global name 'sock' is not defined

标签 python scope global python-2.7

我在我的 Main.py 中定义了一个名为 sock 的套接字。我从 Main.py 导入 Functions.py,其中有一个名为 sendMessage 的函数(或方法,不知道它们在 Python 中是如何调用的)。在 sendMessage 中,我需要使用我在 Main.py 中定义的 socks 。我该怎么做呢?我已经尝试将 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

最佳答案

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

关于python - 名称错误 : global name 'sock' is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9349503/

相关文章:

memory - CUDA 共享内存和全局内存有什么区别?

c# - 我可以声明一个全局变量并从任何地方引用它而不引用它的类吗?

python - 如何使用 pip 从 Bitbucket 安装软件包?

php - 在匿名函数中使用 static::method() 会在 PHP 版本之间产生不同的结果

python - 从回溯中隐藏文件

JavaScript 作用域问题

javascript - 谷歌地图 : Passing extra arguments into GeoCoder for InfoWindows

Python "local variable referenced before assignment"错误尽管全局 key

Python 请求无法处理 403 错误

python - 使用用户提供的脚本解析文本文件的安全方法