win移植linux
阿新 • • 發佈:2020-07-29
win移植linux
python執行shell指令碼
-
os.system("command")
-
os.popen("command")
os.popen() 返回的是一個檔案物件 -
subprocess.call()
print(subprocess.call(["ls","-l"],shell=False)) # shell引數為false,則,命令以及引數以列表的形式給出 a=subprocess.call(["ls","-l"],shell=False) # shell引數為false,則,命令以及引數以列表的形式給出 p = subprocess.Popen('ps aux',shell=True,stdout=subprocess.PIPE) out,err = p.communicate() for line in out.splitlines(): print line
位元組碼與字串轉換
#bytes object byte = b"byte example" # str object str = "str example" # str to bytes 字串轉位元組 bytes(str, encoding="utf8") # bytes to str 位元組轉字串 str(bytes, encoding="utf-8") # an alternative method # str to bytes 字串轉為位元組 str.encode(str) # bytes to str 位元組轉為字串 bytes.decode(bytes)
編碼相關
# 編碼型別轉換, gbk轉utf-8
iconv -f gbk -t utf8 target.txt
# 可以通過vim檢視與修改檔案編碼格式
:set fileencoding
:set fileencoding=utf-8
# 檢視檔案編碼格式
enca -i -L chinese target.txt
出現:iconv: illegal input sequence at position
一般是檔案編碼型別不正確。
指令碼
#!/usr/bin/env python3 import os import subprocess suffix = ['cpp', 'h'] for file in os.listdir('./'): if any( file.find(fix) != -1 for fix in suffix ): cmd = "enca -i -L chinese " + file p = subprocess.Popen( cmd, shell=True, stdout=subprocess.PIPE ) out, err = p.communicate() for line in out.splitlines(): fmt = str(line, encoding='utf-8') cmd = "iconv -f " + fmt + " -t utf8 " + file + " > 2.txt" subprocess.call( cmd, shell=True ) cmd = "cat 2.txt > " + file subprocess.call( cmd, shell=True )