如何使 Python "not recognized as an internal or external command" 成为例外
How to make Python "not recognized as an internal or external command" an exception
我有这段代码:
path = askdirectory(title='Choose folder')
os.chdir(path)
try:
os.system('currency.py')
except:
#Error message
ctypes.windll.user32.MessageBoxW(0, u"Error", u"Error", 0)
我想要完成的是,当用户选择了错误的文件夹('currency.py' 文件不在其中的文件夹)时,它会抛出这个小错误消息框。
相反,当我故意选择错误的文件夹时,它会显示:
"currency.py "未被识别为内部或外部命令
但它没有向我显示错误 window。有没有办法让 python 将此错误识别为异常?谢谢!
您可以尝试侦听 %ErrorLevel%
代码中与 0
不同的任何内容(成功),如果匹配,则 raise Exception
.
它会像这样工作,例如:
if os.system('currency.py'):
raise Exception
您似乎正在使用 Python 到 运行 使用操作系统 shell 的 Python 文件。
您可以通过导入文件并(如果需要)实例化它来 运行 文件。
try:
# import the python file
import currency.py
# instantiate the class/function if required
except ImportError:
ctypes.windll.user32.MessageBoxW(0, u"Error", u"Error", 0)
尽管如此,您可以通过查看文件是否存在来避免使用 try/catch 场景,如果不存在,则显示您的错误消息:
if os.path.isfile(file_path):
os.system('currency.py')
else:
ctypes.windll.user32.MessageBoxW(0, u"Error", u"Error", 0)
我有这段代码:
path = askdirectory(title='Choose folder')
os.chdir(path)
try:
os.system('currency.py')
except:
#Error message
ctypes.windll.user32.MessageBoxW(0, u"Error", u"Error", 0)
我想要完成的是,当用户选择了错误的文件夹('currency.py' 文件不在其中的文件夹)时,它会抛出这个小错误消息框。 相反,当我故意选择错误的文件夹时,它会显示:
"currency.py "未被识别为内部或外部命令
但它没有向我显示错误 window。有没有办法让 python 将此错误识别为异常?谢谢!
您可以尝试侦听 %ErrorLevel%
代码中与 0
不同的任何内容(成功),如果匹配,则 raise Exception
.
它会像这样工作,例如:
if os.system('currency.py'):
raise Exception
您似乎正在使用 Python 到 运行 使用操作系统 shell 的 Python 文件。 您可以通过导入文件并(如果需要)实例化它来 运行 文件。
try:
# import the python file
import currency.py
# instantiate the class/function if required
except ImportError:
ctypes.windll.user32.MessageBoxW(0, u"Error", u"Error", 0)
尽管如此,您可以通过查看文件是否存在来避免使用 try/catch 场景,如果不存在,则显示您的错误消息:
if os.path.isfile(file_path):
os.system('currency.py')
else:
ctypes.windll.user32.MessageBoxW(0, u"Error", u"Error", 0)