将utf-8输入用于cmd Python模块 [英] Using utf-8 input for cmd Python module

查看:85
本文介绍了将utf-8输入用于cmd Python模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在创建小型CLI笔记本应用程序的过程中,我决定使用 cmd Python库(另请参见在PyMOTW上的 cmd )。

In the process of creating a small CLI notebook application, I decided to go with the cmd Python library (see also cmd on PyMOTW).

我的shell是UTF-8。

My shell is UTF-8.

→ echo $LANG
fr_FR.utf-8
→ echo $LC_ALL
fr_FR.utf-8

它运行良好。

→ echo "東京"
東京

启动我的小应用程序的代码并尝试使用utf-8:

Starting the code of my little app and trying to use utf-8:

→ python nb.py 
log> foobar
2013-01-15 foobar
log> æ±äº¬
2013-01-15 æ±äº¬

已编辑是预期的输入/输出。

Edited The expected input/output is. When I type utf-8 characters, be accent or Japanese characters in that case, I get garbage.

log> 東京
2013-01-15 東京

因此,在启动程序时,命令行会更改

So when starting the program the command line changes the type of the input.

#!/usr/bin/env python2.7
# encoding: utf-8
import datetime
import os.path
import logging
import cmd

ROOT = "~/test/"
NOTENAME = "notes.md"

def todaynotepath(rootpath, notename):
    isodate = datetime.date.today().isoformat()
    isodate.replace("-", "/")
    return rootpath + isodate.replace("-", "/") + "/%s" % (notename)

def addcontent(content):
    logging.info(content)

class NoteBook(cmd.Cmd):
    """Simple cli notebook."""
    prompt = "log> "

    def precmd(self, line):
        # What is the date path NOW
        notepath = todaynotepath(ROOT, NOTENAME)
        # if the directory of the note doesn't exist, create it.
        notedir = os.path.dirname(notepath)
        if not os.path.exists(notedir):
            os.makedirs(notedir)
        # if the file for notes today doesn't exist, create it.
        logging.basicConfig(filename=notepath, level=logging.INFO, format='%(asctime)s - %(message)s')
        return cmd.Cmd.precmd(self, line)

    def default(self, line):
        if line:
            print datetime.date.today().isoformat(), line
            addcontent(line)

    def do_EOF(self, line):
        return True

    def postloop(self):
        print

if __name__ == "__main__":
    NoteBook().cmdloop()

所以我想可能是在cmd的原始Class中要覆盖的东西。我检查了模块,但还没有运气。

So I guess there might be things to override in the original Class of cmd. I checked the module but without luck yet.

编辑2:按照@dda的建议,添加了 LESSCHARSET >

Edit 2: Added LESSCHARSET as recommended by @dda

LANG=fr_FR.utf-8
LANGUAGE=fr_FR.utf-8
LC_ALL=fr_FR.utf-8
LC_CTYPE=fr_FR.UTF-8
LESSCHARSET=utf-8


推荐答案

Karl,您的代码非常适合我。看到以下内容:

Your code works perfectly for me, Karl. See this:

dda$ ./nb.py 
log> tagada
2013-01-15 tagada
log> 香港
2013-01-15 香港
log> 

notes.md 文件包含适当的条目。因此,我认为这不是 cmd 在这里有问题,但可能在您的终端设置中有问题。尝试添加

And the notes.md file contains the proper entries. So I don't think it's cmd that's at fault here, but probably something in your terminal settings. Try adding

export LESSCHARSET=utf-8

在您的 .profile 中。

这篇关于将utf-8输入用于cmd Python模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆