Python 使模块使用主程序中定义的函数和变量
我正在为我的网络制作一个IRC机器人。为了使代码更简洁,我在模块中定义函数。所有这些模块都在一个名为“插件”的文件夹中。一个模块说调用函数sendMsg失败,因为它试图运行主程序中定义的函数。我还希望这个模块能够在程序启动后访问主程序中定义的变量Python 使模块使用主程序中定义的函数和变量,python,module,irc,Python,Module,Irc,我正在为我的网络制作一个IRC机器人。为了使代码更简洁,我在模块中定义函数。所有这些模块都在一个名为“插件”的文件夹中。一个模块说调用函数sendMsg失败,因为它试图运行主程序中定义的函数。我还希望这个模块能够在程序启动后访问主程序中定义的变量 import socket import time import re from plugins.say import * host = "irc.somenetwork.net" port = 6667 nick = "ircbot" chann
import socket
import time
import re
from plugins.say import *
host = "irc.somenetwork.net"
port = 6667
nick = "ircbot"
channels = "##bottesting"
s = socket.socket()
def connect():
s.connect((host, port))
s.send("NICK %s\r\n" % nick)
s.send("USER %s %s nul :%s\r\n" % (nick, nick, nick))
time.sleep(3)
s.send("JOIN %s\r\n" % channels)
time.sleep(3)
def sendMsg(chan, msgSend):
s.send("PRIVMSG %s :%s\r\n" % (chan,msgSend))
# print "Sending message \"%s\" to channel/user \"%s\"" % (msgSend, chan)
def quitServ(quitMsg="m8bot"):
s.send("QUIT %s\r\n" % quitMsg)
connect()
while 1:
msgRaw = s.recv(1024)
print msgRaw
if msgRaw == "":
break
if "PING" in msgRaw:
print "Pong!"
PONG = msgRaw.split(' ')
PONG[0] = PONG[0].replace('PING','PONG')
PONG = ' '.join(PONG)
s.send("%s\r\n" % PONG)
if "PRIVMSG" in msgRaw:
# print "PRIVMSG detected"
user = ''.join(re.compile("(?<=:).{0,}(?=.{0,}!)").findall(msgRaw.split(' ')[0]))
channel = msgRaw.split(' ')[2]
command = (' '.join(msgRaw.split(' ')[3:]).replace(":","",1)).split(' ')[0]
msg = ''.join((' '.join(msgRaw.split(' ')[3:]).replace(":","",1)).split(' ')[1:]).replace("\r\n","")
if not "#" in channel:
channel = user
print "Nick: %s\nChannel: %s\nCommand: %s\nMsg: %s" % (user,channel,command,msg)
if ".quit" in command:
if msg:
quitServ(str(msg))
else:
quitServ()
if ".hello" in command:
# print "Attempting to send Hello World message."
sendMsg(channel, "Hello World!")
if ".say" in command:
say(msg)
quitServ()
我知道问题出在哪里,但我不知道该如何解决。感谢反馈:)
-Nia在say.py中尝试导入
main\uuuu
。
然后你的say函数应该是这样的:
def say():
__main__.sendMsg(channel, "You said: %s" % msg)
但这不是最好的解决方案。只需少量代码更改即可解决问题
def say():
__main__.sendMsg(channel, "You said: %s" % msg)