我在我的 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/