」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何在 Python 的 `os.system()` 呼叫中正確轉義指令參數?

如何在 Python 的 `os.system()` 呼叫中正確轉義指令參數?

發佈於2024-11-02
瀏覽:622

How to Properly Escape Command Arguments in Python\'s `os.system()` Calls?

轉義os.system() 呼叫中的指令參數

在Python 中使用os.system() 時,請確保正確的參數處理是至關重要的。檔案和其他參數通常需要轉義以防止幹擾 shell 的命令。以下是有效轉義各種作業系統和shell(尤其是bash)參數的綜合指南:

使用引號

最簡單的解決方案是將參數括在引號中。單引號(') 防止shell 擴展,而雙引號(") 允許變數替換,但抑制引號的字串內的變數擴展。這種方法在不同平台和shell 中得到廣泛支持,包括bash:

os.system("cat '%s' | grep something | sort > '%s'" 
          % (in_filename, out_filename))

使用shlex模組

Python提供了專為此目的設計的shlex模組。它的 quote() 函數正確地轉義字串以在 POSIX shell 中使用,包括 bash:

import shlex

escaped_in_filename = shlex.quote(in_filename)
escaped_out_filename = shlex.quote(out_filename)
os.system("cat {} | grep something | sort > {}".format(
          escaped_in_filename, escaped_out_filename))

使用Pipes 模組(棄用警告!)

對於Python 版本2.x 和3.x 直至3.10,pipes.quote 來自已已棄用的Pipes 模組可以用作shlex.quote 的替代品。請注意,從 Python 3.11 開始,管道被標記為刪除:

from pipes import quote

escaped_in_filename = quote(in_filename)
escaped_out_filename = quote(out_filename)
os.system("cat {} | grep something | sort > {}".format(
          escaped_in_filename, escaped_out_filename))

作為一般規則,出於安全原因,使用者產生的輸入不應在未經適當驗證和清理的情況下直接插入系統呼叫中。

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3