1

windows下python下,py脚本(test.py),os.system或subprocess.Popen调用dos命令失败,命令行下成功(windows->cmd.exe),脚本如下附加信息:

  • 1.dos(windows->cmd.exe)编码为'cp936',属于'gbk'
  • 2.我用notepad++把test.py解码成utf-8
  • 3 .decode('gbk'), .encode('gbk'), .decode('utf-8'), .enode('utf-8') 都试过了
  • 4.不知道为什么
  • 错误信息:

        C:\Python27\python.exe E:/XtTradeClient/test.py
        File "E:/XtTradeClient/test.py", line 5 
        SyntaxError: Non-ASCII character '\xba' in file E:/XtTradeClient/test.py on line 5,but no encoding declared; see http://www.python.org/peps/pep-0263.html for details
    
        Process finished with exit code 1
    
        -------------------------------------------------------------------------------
        # encoding='utf-8'
        import os
    
        if __name__ == "__main__":
            info = '汉字'
            cmd = 'echo ' + info
            if 0 != os.system(cmd):
                raise Exception('failed to call 'echo in command')
        -------------------------------------------------------------------------------
    
    4

    2 回答 2

    1

    显示的错误来自缺少编码注释。好像您尝试添加一个,但格式错误,因此无法识别。尝试:

    # encoding: utf-8
    

    那么下一个问题可能是 shell 期望的编码。如果您的源代码保存为 UTF-8,那么其中的(字节)字符串将采用 UTF-8 编码并以这种方式传递给os.system(). 您可能必须为实际将这些字节显示为字符的应用程序重新编码。即:在终端的编码中先从UTF-8解码到unicode再从unicode到a str。通过使用 unicode 文字可以避免显式解码,至少对于字符超出 ASCII 范围的(字节)字符串。

    # encoding: utf-8
    import os
    
    
    def main():
        info = u'汉字'
        cmd = 'echo ' + info
        if not os.system(cmd.encode('gbk')):
            raise Exception('failed to call `echo` command')
    
    
    if __name__ == '__main__':
        main()
    
    于 2014-07-10T15:11:34.047 回答
    0

    您的编码魔术注释不正确。将其更改为#-*- coding=utf-8 -*-.

    有关更多信息,请参阅pep 0263

    于 2014-07-10T15:07:45.967 回答