![](/img/trans.png)
[英]Correct way in Python to write a bash for loop with `subprocess`
[英]Correct way to escape a subprocess call in python
我在正確轉義子流程調用時遇到問題
我想調用sed -n "$=" /path/to/file
來計算sed -n "$=" /path/to/file
中的行數,但是無法從python進行。 我的代碼如下:
import subprocess
filename = "/path/to/file"
cmd = subprocess.Popen(["sed", "-n '$='", filename], stdout=subprocess.PIPE)
cmd_out, cmd_err = cmd.communicate()
num_lines = int(cmd_out.strip())
print num_lines
我曾嘗試對“ -n'$ ='”使用不同的轉義組合,但似乎無濟於事。
-n
和$=
是兩個單獨的參數。
["sed", "-n", "$=", filename]
默認情況下,subprocess.Popen具有shell = False。
在不調用shell的情況下,每個參數都未經解釋地傳遞給sed,因此sed將參數讀為-n'$ ='
當您運行命令sed -n'$ ='時,shell會在發送到命令sed之前刪除''。
因此,您的$ =應該沒有引號
並且按照Ignacio的指定,-n $ =參數應該分開
cmd = subprocess.Popen(["sed", "-n", "$=", filename], stdout=subprocess.PIPE)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.