私のプログラムはsubprocess
、optparse
モジュールを使用して端末出力を読み取り、印刷します。
Python 2(2.7.14+)の結果は問題ありませんが、Python 3(3.6.7)では1行であり、読み取ることができません。
リストから文字列に変換しようとしました
print(str(ifconfig_result))
ループしてみました
for result in ifconfig_result :
print(result)
無駄に。
これは私のコードです
import subprocess
import optparse
def get_arguments():
parser = optparse.OptionParser()
parser.add_option("-i","--interface",dest="interface",help="interface to change its MAC address")
parser.add_option("-m","--mac",dest="new_mac",help="new MAC address")
(options,arguments) = parser.parse_args()
if not options.interface:
parser.error("[-] Plase specify an interface, use --help for more info.")
elif not options.new_mac:
parser.error("[-] Plase specify a mac, use --help for more info.")
return options
def change_mac(interface, new_mac):
print("[+] Changing MAC address for " + interface + " to "+ new_mac)
subprocess.run("ifconfig "+interface+" down", shell=True)
subprocess.run("ifconfig "+interface+" hw ether "+new_mac, shell=True)
subprocess.run("ifconfig "+interface+" up",shell=True)
options= get_arguments()
ifconfig_result = subprocess.check_output(["ifconfig", options.interface])
print(ifconfig_result)
Python2の出力:
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 10.0.2.4 netmask 255.255.255.0 broadcast 10.0.2.255
inet6 AAAAA prefixlen 64 scopeid 0x20<link>
ether AAAAA txqueuelen 1000 (Ethernet)
RX packets 12176 bytes 17869942 (17.0 MiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 3507 bytes 213850 (208.8 KiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
しかし、私の出力は表示されています
b'eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500\n inet 10.0.2.4 netmask 255.255.255.0 broadcast 10.0.2.255\n inet6 AAAAA prefixlen 64 scopeid 0x20<link>\n ether AAAAA txqueuelen 1000 (Ethernet)\n RX packets 12179 bytes 17870182 (17.0 MiB)\n RX errors 0 dropped 0 overruns 0 frame 0\n TX packets 3510 bytes 214090 (209.0 KiB)\n TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0\n\n'
python 3では、あなたはバニラ、文字列、しかし店は、エスケープシーケンスをバイナリ文字列だけではなく、持っている'\n'
ためのスタンドで改行を。この文字列を通常どおりに処理するには、デコードします。最小限の例:
>>> string = b"Hello \n World"
>>> print(string)
>>> b'Hello \n World'
>>> string = string.decode('ascii') # sring decoding
>>> print(string)
Hello
World
>>>
この質問も見てください:Python3で「バイナリ文字列」を通常の文字列に変換する方法は?
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加