【问题标题】:How to make Python "not recognized as an internal or external command" an exception如何使 Python“不被识别为内部或外部命令”异常
【发布时间】:2021-03-11 05:31:25
【问题描述】:

我有这段代码:

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”不被识别为内部或外部命令

但它没有显示错误窗口。有没有办法让python将此错误识别为异常?谢谢!

【问题讨论】:

  • 也许这个错误是因为你忘记了python?换句话说,改变os.system('currency.py')````to os.system('python currency.py')````并报告你得到了什么。
  • 尝试使用os.startfile() 而不是os.system()..

标签: python exception cmd path system


【解决方案1】:

您似乎正在使用 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)

【讨论】:

    【解决方案2】:

    您可以尝试侦听%ErrorLevel% 代码以获取与0 不同的任何内容(成功),如果匹配,则为raise Exception。

    它会像这样工作,例如:

    if os.system('currency.py'):
        raise Exception
    

    【讨论】:

      猜你喜欢
      • 2021-09-15
      • 2021-02-08
      • 1970-01-01
      • 2013-01-04
      • 2014-10-21
      • 2014-02-08
      • 2017-08-22
      • 1970-01-01
      相关资源
      最近更新 更多