将一个脚本导入另一个脚本

2 投票
1 回答
9048 浏览
提问于 2025-04-16 10:34

我正在尝试将这个文件导入到另一个文件中。

http://pastebin.com/bEss4J6Q

目标是把它导入到这个文件里:

def MainLoop(self): #MainLoop is used to make the commands executable ie !google !say etc;
                try:
                    while True:
                        # This method sends a ping to the server and if it pings it will send a pong back
                        #in other clients they keep receiving till they have a complete line however mine does not as of right now
                        #The PING command is used to test the presence of an active client or
                        #server at the other end of the connection.  Servers send a PING
                        #message at regular intervals if no other activity detected coming
                        #from a connection.  If a connection fails to respond to a PING
                        #message within a set amount of time, that connection is closed. A
                        #PING message MAY be sent even if the connection is active.
                        #PONG message is a reply to PING message.  If parameter <server2> is
                        #given, this message will be forwarded to given target.  The <server>
                        #parameter is the name of the entity who has responded to PING message
                        #and generated this message.

                        self.data = self.irc.recv( 4096 )
                        print self.data
                        if self.data.find ( 'PING' ) != -1:
                            self.irc.send(( "PONG %s \r\n" ) % (self.data.split() [ 1 ])) #Possible overflow problem

                        if "!chat" in self.data:
                            ..... 

这样我就可以在每次调用'!chat'时成功使用导入的文件(ipibot)。

但是我不太确定该怎么写。这是我目前的进展:

 if "!chat" in self.data:
      user = ipibot.ipibot()
      user.respond

我想说我已经看过Python的模块部分以及导入的相关内容,但我似乎还是没能完全理解。

我理解的顺序是:文件 -> 类 -> 函数。

1 个回答

4

模块其实就是一个Python源文件。你把这个Python源文件放在和其他源文件同一个文件夹里,就可以在其他源文件中导入这个模块。当你导入这个模块时,里面定义的类和函数就可以用来调用了。

比如,在你的情况下,你只需要在源文件的顶部写上

import ipibot

只要确保ipibot.py(你的粘贴板文件)在同一个文件夹里,或者在PYTHONPATH(这是一个Python程序查找模块的标准目录)中,然后就可以开始使用ipibot.ipibot()来调用这个模块里的ipibot()函数。就这么简单。

撰写回答