python轉義字串for shell command line
最近使用os.system(shell_string)執行外部命令的時候,總會爆出各種奇葩的錯誤提示,查到最後還是個執行命令的字串轉移問題,比如你執行的命令為
python arg1 arg2 ....
這裡arg1裡面如果包含了' " &等特殊字元的時候,需要先進行字串替換
def shellquote(s):
"""
轉義字串
"""
return "'" + s.replace("'", "'\\''") + "'"
這樣把你的引數用引號擴起來,然後轉移字串裡面的引號就可以了~