将脚本导入另一个脚本

时间:2011-01-25 03:17:53

标签: python module import

我正在尝试导入此文件

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:
                            ..... 

这样我就可以成功调用导入的文件(ipibot) self.data中的'!chat':#被调用。

但我不确定如何写它。这就是我到目前为止所拥有的

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

我想说明我已经看过Python的模块部分以及导入我似乎无法掌握它我猜?

file - &gt; class - &gt;功能是我理解的。

1 个答案:

答案 0 :(得分:4)

模块只是一个python源文件。您将该python源文件保存在与其他源文件相同的目录中,并且可以将该模块导入其他源文件中。导入该模块时,可以使用该模块中定义的类和函数。 对于例如在你的情况下,你只会做

import ipibot

在源代码的顶部,前提是ipib​​ot.py(你的pastebin)文件存在于同一目录或PYTHONPATH(python程序可以查找模块的标准目录),然后开始使用{ {1}}使用该模块中的函数ipibot.ipibot()。多数民众赞成。