python中name没有定义_python – NameError:未定义全局名称’sock’

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

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,scope,python-2-7,global

来源: https://codeday.me/bug/20190726/1539930.html

你可能感兴趣的:(python中name没有定义)