0

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

1 Answers1

0
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)

Amadan
  • 191,408
  • 23
  • 240
  • 301
  • Yeah but when you do this it opens up another console window so how di I make it so it runs in the console I executed it from? – user3308930 Feb 14 '14 at 07:44
  • If you're running `system.os()` under Windows, shell by default opens a window. Try the approach mentioned [here](http://stackoverflow.com/questions/1016384/cross-platform-subprocess-with-hidden-window/) if you really need it, or replace with `subprocess.call` with `Shell=False`. Read more on [subprocess](http://docs.python.org/2/library/subprocess.html#subprocess-replacements) since `os.system` is kind of not recommended, per Python docs. All of this is avoided if you execute Python as Python (using `importlib`). – Amadan Feb 14 '14 at 07:54