Python脚本打印unicode,在shell中使用``导致错误

时间:2017-04-03 19:35:55

标签: python bash python-2.7 unicode

我有一个名为a.py的Python脚本:

WITH dates as(
    SELECT * FROM generate_series('2016-02-01'::date, '2016-06-01'::date,
  '1 month'::interval)
),
step AS (
    SELECT a.Id, 
    'Raw' AS Step,
    a.Created_at AS FDate,
    b.TDate
    FROM sales a
    LEFT JOIN 
    (SELECT 
    a.Id,
    CASE WHEN a.lastmodified IS NULL THEN now() ELSE a.lastmodified END AS TDate
    FROM sales a
    WHERE a.lastmodified IS NOT NULL AND a.Status like 'Raw') b
    ON a.Id = b.Id
    WHERE a.created_at IS NOT NULL

    UNION
    SELECT a.Id,  
    'Lost' AS Step,
    a.lastmodified AS FDate,
    b.TDate
    FROM sales a
    LEFT JOIN 
    (SELECT a.Id, 
    CASE WHEN a.lastmodified IS NULL THEN now() ELSE a.lastmodified END AS ToDate
    FROM sales a
    WHERE a.closed_at IS NOT NULL AND a.Status like 'Finished') b
    ON a.Id = b.Id
    WHERE a.lastmodified IS NOT NULL AND a.Status like 'Lost'

    UNION
    SELECT a.Id, 
    'Finished' AS Step,
    a.closed_at::date AS FDate,
    now() AS TDate
    FROM sales a
    WHERE a.closed_at IS NOT NULL AND a.Status like 'Finished'
)
    SELECT DISTINCT to_char(d.generate_series::date, 'YYYY-MM') AS date, s.Step AS Status,
    COUNT(s.Step) OVER (PARTITION BY s.Step ORDER BY to_char(d.generate_series, 'YYYY-MM')) AS count_id
    FROM dates d
    LEFT JOIN step s
    ON to_char(d.generate_series::date,'YYYY-MM') = to_char(s.FDate::date, 'YYYY-MM')
    ORDER BY date ASC

在bash和tcsh:

#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
print u''

错误来自Python,而不是shell。如何在反引号下运行脚本会影响脚本本身?请注意,如果我在脚本开头将解释器切换到Python 3,这不是问题。

1 个答案:

答案 0 :(得分:7)

当Python没有检测到它正在打印到终端时,就像子shell中的情况一样,sys.stdout.encoding设置为None。打印unicode时,使用ascii编解码器(至少在Python2中)。如果unicode包含0-127之外的代码点,则会导致UnicodeError。

解决此问题的方法是将PYTHONIOENCODING环境变量设置为适当的编码。例如:

export PYTHONIOENCODING=utf-8; echo `a.py`

此信用转到unutbu