6

非常に良いです。スレッドの出力に少し問題があります。Unicode で取得するか、utf-8 に変換できないと思います。これがコードです。

import subprocess,sys,time

string = b'dir'
process = subprocess.Popen('cmd.exe', shell=True,cwd="C:\\",stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=None)
process.stdin.write(string)
o,e=process.communicate()
process.wait()
process.stdin.close()
print (o.encode('utf-8'))

次のエラーをジャンプします。

**Traceback (most recent call last):
  File "C:\Documents and Settings\francisco\Escritorio\k.py", line 12, in <module>
    print (o.encode(utf-8))
AttributeError: 'bytes' object has no attribute 'encode'**

印刷物を残して印刷し、あなたが私に許可した場合:

print(o)

ただし、次のように出力されます。

**b'Microsoft Windows XP [Versi\xa2n 5.1.2600]\r\n(C) Copyright 1985-2001 Microsoft Corp.\r\n\r\nC:\\>\xa8M\xa0s? '**

そして、これらの2行を変更すると:

string = bytes('dir',encoding="utf-8") 
print (n[0].decode("latin"))

出力の一部のみを印刷します

それは失敗しますか?


私はこのように解決しました:

process.stdin.write("dir\n".encode())
o,e=process.communicate()
print (o.decode("utf-8"))

しかし、私はエラーが発生します:

トレースバック (最新の呼び出しが最後): ファイル "C:\Documents and Settings\francisco\Escritario\k.py"、6 行目、出力 (o.decode("utf-8")) UnicodeDecodeError: 'utf-8'コーデックは位置 103 のバイト 0xa3 をデコードできません: 無効な開始バイト

次のように印刷します。

print (o.decode("latin"))

ラテン語では、このエラーを修正して utf-8 で出力できますか?

4

1 に答える 1

11

o、からの最初の戻り値はproc.communicate()、すでに ではbytesないstrため、すでに何らかのエンコーディングでエンコードされています (または、単なるバイトのシーケンスと考えることができます)。

Python3では、 にデコードでき、にエンコードbytesできますが、エンコードもデコードもできません。それがPython3が不平を言っている理由です、strstrbytesbytesstr

AttributeError: 'bytes' object has no attribute 'encode'
于 2013-05-25T14:37:36.613 に答える