Python: Run Script Under Same Window
Question: I am trying to setup a program where when someone enters a command it will run
that command which is a script in a sub folder called "lib".

Here is my code:

    
    
    import os
    
    while 1:
        cmd = input(' >: ')
        for file in os.listdir('lib'):
            if file.endswith('.py'):
                try:
                    os.system(str(cmd + '.py'))
                except FileNotFoundError:
                    print('Command Not Found.')
    

I have a file: lib/new_user.py But when I try to run it I get this error:

    
    
    Traceback (most recent call last):
       File "C:/Users/Daniel/Desktop/Wasm/Exec.py", line 8, in <module>
         exec(str(cmd + '.py'))
       File "<string>", line 1, in <module>
     NameError: name 'new_user' is not defined
    

Does anyone know a way around this? I would prefer if the script would be able
to be executed under the same window so it doesn't open a completely new one
up to run the code there. This may be a really Noob question but I have not
been able to find anything on this.

Thanks,

Daniel Alexander


Answer: 
    os.system(os.path.join('lib', cmd + '.py'))
    

You're invoking `new_user.py` but it is not in the current directory. You need
to construct `lib/new_user.py`.

(I'm not sure what any of this has to do with windows.)

However, a better approach for executing Python code from Python is making
them into modules and using `import`:

    
    
    import importlib
    cmd_module = importlib.import_module(cmd, 'lib')
    cmd_module.execute()
    

(Assuming you have a function `execute` defined in `lib/new_user.py`)

