我在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
.php
。 - RobinJ