Python 在调用连接后甚至不会打印测试字符串。虽然以代码 0 执行
Python will not print even test strings after calling a join. Executes with code 0 though
我正在编写一些 Python 代码来重命名一些文件。这样做时,我 运行 遇到了一个奇怪的错误。当我在加入后尝试打印任何内容时,什么也不会打印。甚至 print 'test'
.
这可能是什么原因造成的?
这是代码:
... #finding all images in a .html
for t in soup.find_all('img'): # Note: soup exists outside of with
try:
old_src = t['src'] # Access src attribute
image = os.path.split(old_src)[1] # Get file name
#print 'image => ' + image
relpath = os.path.relpath(root, do) # Get relative path from do to root
folders = relpath.strip('\').split('\') # Remove outer slashes, split on folder separator
#BELOW LINE CAUSES PROBLEM
new_src = '_'.join(folders.append(str(image))) # Join folders and image by underscore
print t['src'] #prints nothing
print 'test' #prints nothing
t['src'] = new_src # Modify src attribute
except: # Do nothing if tag does not have src attribute
pass
令我困惑的是,此行下方没有打印任何内容,因为它显然已到达执行结束...尽管据我所知,它不会在此行之后执行任何操作。执行完全停止。
有人能看到这里有什么问题吗?
谢谢。
folders.append(str(image))
returns 什么都没有 (None
),因此程序会引发异常并跳过您的 print
语句。
您只需将 new_src = '_'.join(folders.append(str(image)))
替换为以下两行即可解决此问题:
folders.append(str(image))
new_src = '_'.join(folders)
如果您通过 except Exception as e:
和 print e
捕获异常,您将看到 TypeError 错误消息,因为它与通过执行 '_'.join(folders.append(str(image)))
[=19 来执行 '_'.join(None)
相同=]
假设 folders
是一个普通的 list
、folders.append
returns None
,但是 str.join
期望一个可迭代的参数,所以它引发了一个 TypeError
... 然后被你的 except: pass
捕获并忽略,之后继续执行下一个 t in soup.find_all('img')
,因此永远不会达到 print
.
我正在编写一些 Python 代码来重命名一些文件。这样做时,我 运行 遇到了一个奇怪的错误。当我在加入后尝试打印任何内容时,什么也不会打印。甚至 print 'test'
.
这可能是什么原因造成的? 这是代码:
... #finding all images in a .html
for t in soup.find_all('img'): # Note: soup exists outside of with
try:
old_src = t['src'] # Access src attribute
image = os.path.split(old_src)[1] # Get file name
#print 'image => ' + image
relpath = os.path.relpath(root, do) # Get relative path from do to root
folders = relpath.strip('\').split('\') # Remove outer slashes, split on folder separator
#BELOW LINE CAUSES PROBLEM
new_src = '_'.join(folders.append(str(image))) # Join folders and image by underscore
print t['src'] #prints nothing
print 'test' #prints nothing
t['src'] = new_src # Modify src attribute
except: # Do nothing if tag does not have src attribute
pass
令我困惑的是,此行下方没有打印任何内容,因为它显然已到达执行结束...尽管据我所知,它不会在此行之后执行任何操作。执行完全停止。
有人能看到这里有什么问题吗?
谢谢。
folders.append(str(image))
returns 什么都没有 (None
),因此程序会引发异常并跳过您的 print
语句。
您只需将 new_src = '_'.join(folders.append(str(image)))
替换为以下两行即可解决此问题:
folders.append(str(image))
new_src = '_'.join(folders)
如果您通过 except Exception as e:
和 print e
捕获异常,您将看到 TypeError 错误消息,因为它与通过执行 '_'.join(folders.append(str(image)))
[=19 来执行 '_'.join(None)
相同=]
假设 folders
是一个普通的 list
、folders.append
returns None
,但是 str.join
期望一个可迭代的参数,所以它引发了一个 TypeError
... 然后被你的 except: pass
捕获并忽略,之后继续执行下一个 t in soup.find_all('img')
,因此永远不会达到 print
.