0
我試圖設置一個程序,當有人輸入命令時,它將運行該命令,該命令是名爲「lib」的子文件夾中的腳本。Python:在同一窗口下運行腳本
這裏是我的代碼:
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.')
我有一個文件:LIB/new_user.py但是當我嘗試運行它,我得到這個錯誤:
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
有誰知道一種方法在這附近?我寧願如果腳本能夠在同一窗口下執行,所以它不會打開一個全新的腳本來運行代碼。這可能是一個真正的Noob問題,但我一直沒能找到任何關於此的東西。
感謝,
丹尼爾·亞歷山大
是的,但是當你做到這一點打開了另一個控制檯窗口怎麼這麼二我做它,所以它在我執行它從控制檯上運行? – user3308930
如果你在Windows下運行'system.os()',shell默認打開一個窗口。如果你真的需要它,試試這裏提到的方法[這裏](http://stackoverflow.com/questions/1016384/cross-platform-subprocess-with-hidden-window/),或用'shell'替換'subprocess.call' = FALSE'。閱讀關於[subprocess](http://docs.python.org/2/library/subprocess.html#subprocess-replacements)的更多信息,因爲每個Python文檔都不推薦使用'os.system'。如果您將Python作爲Python執行(使用'importlib'),所有這些都可以避免。 – Amadan