Search code examples
pythonasynchronousdiscord.pyos.walkos.system

Directory isn't found when executing os.walk for the second time


I have this function

def start(name):
for folder in next(os.walk("./hosted"))[1]:
    if folder == name:
        for file in os.listdir("./hosted/" + folder + "/scripts"):
            if file == "bot.py":
                os.chdir("./hosted/" + folder + "/scripts")
                os.system("python3.8 -c \"from bot import start; start()\" &")
                os.chdir(os.getcwd())

The problem is that when I try to run this function for a second time, an error is raised saying that the directory doesn't exist (it is raised at line 2). I've tried running os.walk outside the function twice and it worked, so it isn't the problem.

This is inside a discord bot. I need to initialize more bots from this one and this is the most useful way I found (I accept suggestions). Because discord.py is an asyncronous library, I need the & inside the os.system for the bot to keep running in the background without blocking the whole main bot, I don't know if there is another non-blocking way of executing python scripts.

Thanks.

PS: I'm running this on linux.


Solution

  • In short, the problem is os.chdir(os.getcwd()) essentially does nothing -- it means "change to the current directory". If you used old = os.getcwd() followed by the first chdir, and replaced that nop with chdir(old), it would probably fit your expectations.

    That said, you'd probably be better off using glob to find the files you're interested in and subprocess to manage other processes, though futures or asyncio might be better solutions, depending on your goals.