【问题标题】:Unused variables in PyCharmPyCharm 中未使用的变量
【发布时间】:2016-04-15 18:54:59
【问题描述】:
if ".jpg" in link or ".png" in link:
    fd = urllib.request.urlopen(link)
    #Checks the dimensions of said image file
    Image_file = io.BytesIO(fd.read())
    with Image.open(Image_file) as im:
        width, height = im.size
    print(im.size)

好的,所以我正在创建一个网络爬虫,它应该下载 1920 x 1080 大小的图像。实际的程序可以工作,但 PyCharm 和 Codacy 说这里没有使用宽度和高度变量:

with Image.open(Image_file) as im:
    width, height = im.size

我想这是对的,因为我稍后不会在代码中调用它们,但我想知道是否有其他方法可以做到这一点,所以在查看代码时我看不到未使用的代码错误。

另一个例子:

with Image.open(Image_file) as im:
                width, height = im.size
            #If the dimensions are 1920 by 1080, it will download the file in Wallpapers/filename_#WALL_#PAGE
            #This format makes it easy to check which images was downloaded from which page
            if(im.size == (1920, 1080)):
                wall += 1
                print("***FOUND***\t" + str(wall))
                urllib.request.urlretrieve(link, "Wallpapers/filename"+ str(wall) +"_" + str(page) +".png")

可能是一个愚蠢的问题,但我感谢所有答案。 :)

【问题讨论】:

  • 那是因为你没有对他们做任何事情......添加一个print(width, height)....它应该消失(不知道你为什么甚至print(im.size)
  • 如果你不调用它们,那你为什么要使用它们?
  • 这是获得正确 im.size 的唯一方法,它们实际上并没有在里面存储任何东西。
  • 如果im.size 是恰好包含两个元素的列表或元组。 widthheight 应该解压它
  • 我打印它的原因是因为它更容易用作示例。它们需要保存在一个元组中。

标签: python python-3.x pycharm unused-variables codacy


【解决方案1】:

此方法可能会为您的目的而简化

例如:

from StringIO import StringIO

imageURL = img.get('src')
fd = urllib.request.urlopen(link)
image_name = imageName + '.bmp'

i = Image.open(StringIO(fd.content))

# i.save(dirName + '/' + image_name)

【讨论】:

  • 这也行得通,但我不得不使用 from io import StringIO,因为 Python 3.x 没有 StringIO 模块。谢谢你的帮助! :)
【解决方案2】:

我的解决方案

通过交换

with Image.open(Image_file) as im:
            width, height = im.size

im = Image.open(Image_file)

效果好多了。 :)

【讨论】:

  • 我知道这是一个旧线程,但这是一个危险的更改,因为它不会关闭文件。相反,只需将width, height = im.size 更改为image_size = im.size 并使用image_size,您将使用im.size。这样文件就可以正确关闭,并且您可以在需要时使用元组并且没有未使用的变量。
猜你喜欢
  • 1970-01-01
  • 2015-12-12
  • 2016-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-13
  • 2022-08-12
  • 1970-01-01
相关资源
最近更新 更多