【问题标题】:Python inserting additional \'s?Python插入额外的\'s?
【发布时间】:2012-12-06 13:32:27
【问题描述】:

背景:我在 Eclipse SDK 4.2.1 (Juno) 中使用 python 3.2,我注意到一些奇怪的事情 - 虽然我的程序在 Eclipse 中完美运行,但如果我从文件管理器打开它们,它们总是会出现错误关闭.我设法在 cmd 关闭之前获得了截图:

程序似乎在“images”和“Cy.png”之间插入了一个额外的“\”。但是,我不能只从我的程序中删除一个斜杠 - 在其中,我使用了两个斜杠,因为您需要在字符串中包含一个斜杠。 我的程序如下:

from PIL import Image

def pathConstruction(count, imageName):
    l = []
    l.append('images\\')
    if count == 1:
        l.append('Sepia')
    l.append(imageName)
    imagePath = ''.join(l)
    return imagePath

def grayscale(pix, width, height):
    for col in range(width):
        for row in range(height):
            r,g,b = pix[col, row]
            avg = ((r + g + b) / 3)
            r = int(avg)
            g = int(avg)
            b = int(avg)
            pix[col, row] = r,g,b

def sepia(pix, width, height):
    for col in range(width):
        for row in range(height):
            r,g,b = pix[col, row]
            newR = (r * 0.393 + g * 0.769 + b * 0.189)
            newG = (r * 0.349 + g * 0.686 + b * 0.168)
            newB = (r * 0.272 + g * 0.534 + b * 0.131)
            pix[col, row] = int(newR),int(newG),int(newB)

imageName = input("Please input the full name of your image, including extension: ")
count = 0
imagePath= pathConstruction(count, imageName)
count = count + 1

img = Image.open(imagePath)
pix = img.load()
width, height = img.size

grayscale(pix, width, height)
sepia(pix, width, height)

imagePath = pathConstruction(count, imageName)
img.save(imagePath)
img.show()

问题:如何在 Eclipse 之外运行此程序?

【问题讨论】:

  • 您可以将sys.excepthook 设置为将未捕获的异常记录到文件的函数。无需等待程序退出即可登录文件,设置:logging.basicConfig(filename='example.log',level=logging.DEBUG),登录:logging.info('message')
  • 我确定了实际问题 - 问题已相应更新。
  • 配置日志并在input()之后添加logging.debug(repr(imageName))。您是否在 example.log 中的图像名称处看到 \r
  • 是的,图片名称后面有一个\r,如图所示。

标签: eclipse python-3.x special-characters


【解决方案1】:

我认为问题不在于您在目录和文件名之间看到的额外反斜杠(我认为它只是来自字符串的repr),而是最后添加的\r .我不知道为什么你会在 input 的值中包含它,但你可以通过在字符串上调用 strip 来删除它。

【讨论】:

  • 你能解释一下在字符串上调用strip是什么意思吗?
  • imageName 字符串末尾有回车。从input(例如imageName = input("whatever").strip(),或类似的东西)取回它后,调用strip。如果文件名只是有一个额外的` it would have still worked (on Windows, at least). The base IOError`,如果文件名只是简单的,你也不会得到没有提到正确的东西(如果你给的名字下面没有任何东西,你会得到一个FileNotFoundError)。
【解决方案2】:

只需使用内置的 os.path 模块。它会更简单,更可靠。

def pathConstruction(count, imageName):
    import os
    dir = "images"
    if count == 1:
        imageName = "Sepia" + imageName
    return os.path.join(dir, imageName)

【讨论】:

  • 这仍然得到与以前相同的回溯/IOError,它插入了第二个`\`。
  • 有趣。如果将原始代码中的“images\\”替换为r“images\”,是否得到相同的结果?
  • 如果你的意思是使用l.append(r'images\\'),那么我得到一个错误:IOError: [Errno 22] Invalid argument: 'images\\\\Cy.png\r'
  • 不,使用原始字符串(由 r 前缀表示),您只需要一个反斜杠。虽然你所做的结果表明它也不起作用。
  • 最后一个问题:如果使用正斜杠而不是反斜杠会怎样?
猜你喜欢
  • 1970-01-01
  • 2013-12-26
  • 1970-01-01
  • 2013-09-06
  • 2016-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多