Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 异常被延迟抛出_Python_Exception - Fatal编程技术网

Python 异常被延迟抛出

Python 异常被延迟抛出,python,exception,Python,Exception,我有以下Python脚本: import sys for filename in sys.argv: with open(filename, mode='r') as f: print("Foobar") 如果我以一个不存在的文件名作为参数启动脚本,我会得到一个异常,正如预期的那样。但是,print()仍在执行,尽管我预计不会执行 Foobar Traceback (most recent call last): File "home/bin/ksp-incre

我有以下Python脚本:

import sys


for filename in sys.argv:
    with open(filename, mode='r') as f:
        print("Foobar")
如果我以一个不存在的文件名作为参数启动脚本,我会得到一个异常,正如预期的那样。但是,
print()
仍在执行,尽管我预计不会执行

Foobar
Traceback (most recent call last):
  File "home/bin/ksp-increment-build", line 16, in <module>
    with open(filename, mode='r') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'asdads'
Foobar
回溯(最近一次呼叫最后一次):
文件“home/bin/ksp增量构建”,第16行,在
将open(filename,mode='r')作为f:
FileNotFoundError:[Errno 2]没有这样的文件或目录:“asdads”

这是为什么?

sys.argv的第一个元素是运行脚本本身的路径,因此可以正确打开脚本


第二个元素是不存在的文件名,它在print函数之前抛出错误

sys.argv的第一个元素是脚本自身运行的路径,因此可以正确打开它

第二个元素是不存在的文件名,它在print函数之前抛出错误

if len(sys.argv)>1:for file in(sys.argv[1:):if file in str(os.walk()):
if len(sys.argv)>1:for file in(sys.argv[1:):if file in str(os.walk()):