Yamajac
Yamajac

Reputation: 83

How to import modules from a separate directory?

I want to import asyncore from a different directory, because I need to make some changes to how asyncore works, and don't want to modify the base file.

I could include it in the folder with my script, but after putting all the modules I need there it ends up getting rather cluttered.

I'm well aware of making a sub directory and putting a blank __init__.py file in it. This doesn't work. I'm not exactly sure what happens, but when I import asyncore from a sub directory, asyncore just plain stops working. Specifically; the connect method doesn't get run at all, even though I'm calling it. Moving asyncore to the main directory and importing it normally removes this problem.

I skimmed down my code significantly, but this still has the same problem:

from Modules import asyncore
from Modules import asynchat
from Modules import socket

class runBot(asynchat.async_chat, object):

    def __init__(self):

        asynchat.async_chat.__init__(self)
        self.connect_to_twitch()

    def connect_to_twitch(self):

        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.connect(('irc.chat.twitch.tv',6667))
        self.set_terminator('\n')
        self.buffer=[]


    def collect_incoming_data(self, data):  
        self.buffer.append(data)    

    def found_terminator(self):
        msg = ''.join(self.buffer)
        print(msg)


if __name__ == '__main__':  


    # Assign bots to channels
    bot = runBot()

    # Start bots
    asyncore.loop(0.001)

I'm sure this is something really simple I'm overlooking, but I'm just not able to figure this out.

Upvotes: 1

Views: 82

Answers (1)

pepr
pepr

Reputation: 20752

Use sys.path.append -- see https://docs.python.org/3/tutorial/modules.html for the details.

Update: Try to put a debug print to the beginning and end of sources of your modules to see whether they are imported as expected. You can also print __file__ attribute for the module/object that you want to use to see, whether you imported what you expected -- like:

import re
#...
print(re.__file__)

Upvotes: 0

Related Questions