最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】Python出错:ValueError invalid x escape

Python crifan 3663浏览 0评论

在折腾:

【已解决】Python中的doc string如何写和标准格式是什么

期间,给crifanLib.py新增如下代码:

def getBasename(fullFilename):
    “””
    get base filename
    Examples:
        xxx.exe          -> xxx.exe
        xxx              -> xxx
        Mac/Linux:
           your/path/xxx.py -> xxx.py
        Windows:
           your\path\xxx.py -> xxx.py
    “””
    return os.path.basename(fullFilename)
def removeSuffix(fileBasename):
    “””
    remove file suffix
    Examples:
        xxx.exe -> xxx
        xxx -> xxx
    “””
    splitedTextArr = os.path.splitext(fileBasename)
    filenameRemovedSuffix = splitedTextArr[0]
    return filenameRemovedSuffix
def getInputFilename():
    “””
    get input filename, from argv
    Examples:
        AutoOrder.py -> AutoOrder.py
        python AutoOrder.py -> AutoOrder.py
        python AutoOrder/AutoOrder.py -> AutoOrder/AutoOrder.py
    “””
    argvList = sys.argv
    # print “argvList=%s”%(argvList)
    return argvList[0]
def getInputFileBasename(inputFilename = None):
    “””
    get input file’s base name
    Examples:
        AutoOrder.py -> AutoOrder.py
        AutoOrder/AutoOrder.py -> AutoOrder.py
    “””
    curInputFilename = getInputFilename()
    if inputFilename :
        curInputFilename = inputFilename
    # print “curInputFilename=%s”%(curInputFilename)
    inputBasename = getBasename(curInputFilename)
    # print “inputBasename=%s”%(inputBasename)
    return inputBasename
def getInputFileBasenameNoSuffix():
    “””
    get input file base name without suffix
    Examples:
        AutoOrder.py -> AutoOrder
        AutoOrder/AutoOrder.py -> AutoOrder
    “””
    inputFileBasename = getInputFileBasename()
    basenameRemovedSuffix = removeSuffix(inputFileBasename)
    return basenameRemovedSuffix

但是突然发现无法运行了,报错:

    import crifanLib
ValueError: invalid \x escape

然后找了半天,才发现:

原来是:

为了给函数加上doc string,而把:

# your\path\xxx.py -> xxx.py

放到了doc string中:

def getBasename(fullFilename):
    “””
    get base filename
    Examples:
        xxx.exe          -> xxx.exe
        xxx              -> xxx
        Mac/Linux:
           your/path/xxx.py -> xxx.py
        Windows:
           your\path\xxx.py -> xxx.py
    “””

导致python无法解析

“”” \x “””

所以去加上反斜杠,表示此处的\只是普通的字符串,不是转义:

your\path\\xxx.py -> xxx.py

即可正常运行代码了。

【总结】

此处是由于doc string中内容包含\x,python无法解析,所以出错。

把:

def getBasename(fullFilename):
    “””。。。。。
           your\path\xxx.py -> xxx.py
    “””

改为:

def getBasename(fullFilename):
    “””。。。。。
           your\path\\xxx.py -> xxx.py
    “””

即可。

转载请注明:在路上 » 【已解决】Python出错:ValueError invalid x escape

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
89 queries in 0.174 seconds, using 22.11MB memory