对给定的python代码有不同解释的可能原因是什么?
我有一个代码,我可以在一台计算机上没有错误地执行,但它会在另一台计算机上输出错误。python版本相同(2.7.12)。脚本的编码是相同的。我想知道如何解释这一点,因为这是我看到的唯一两个不同代码解释的原因。
下面是使用luigi的代码(这里只是代码的一部分):
class ExampleClass(luigi.postgres.CopyToTable):
def rows(self):
"""
Return/yield tuples or lists corresponding to each row to be inserted.
"""
with self.input()['Data'].open('r') as fobj:
for line in fobj:
yield line.strip('\n').split('\t')
当我在计算机上运行整个代码时,我确实有一个错误(这是由我上面写的代码引起的),我得到如下结果:
IndentationError: unexpected indent
实际上,代码中有空格和制表符的混合。这很容易解决,这里没有问题,但我的问题是:如何解释解释上的差异?
我之所以问这个问题,是因为在用制表符替换空格来解决这个问题后,我得到了其他错误,这些错误也不应该出现,而且更难解决,问题是代码应该是正确的,因为它在另一台计算机上工作,所以我不应该解决这些错误。
为了给出更多细节,这里是我在解决缩进问题后得到的第二个错误(我没有设法解决这个问题):
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: malformed \N character escape
它是由代码的以下部分引起的:
class AnotherClass(ExampleClass):
def copy(self, cursor, file):
if isinstance(self.columns[0], six.string_types):
column_names = self.columns
elif len(self.columns[0]) == 2:
column_names = [c[0] for c in self.columns]
else:
raise Exception('columns must consist of column strings or (column string, type string) tuples (was %r ...)' % (self.columns[0],))
cursor.copy_expert('copy ' + self.table + ' from stdin with header csv delimiter \'' + self.column_separator + '\' null \'''\\\N''\' quote \'''\"''\' ', file)
发布于 2017-06-21 12:38:12
如错误所示
SyntaxError:(unicode错误)“”unicodeescape“”编解码器无法对位置2-3中的字节进行解码:错误的\N字符转义
有问题的行是这一行:
文件(‘copy’+ self.table +‘from stdin with header csv delimiter \'’+ self.column_separator + '\‘null \’\N‘’\‘quote \’\‘',file)
你的"N“应该是小写的,否则不算换行符。试试这个:
cursor.copy_expert('copy ' + self.table + ' from stdin with header csv delimiter \'' + self.column_separator + '\' null \'''\\\n''\' quote \'''\"''\' ', file)
https://stackoverflow.com/questions/44675587
复制