簡體   English   中英

Python 中的 Escaping 轉義序列

[英]Escaping escape sequence in Python

我對 python 有點陌生。 目標是使用子進程解析執行 shell 命令並從 shell 檢索打印的 output。 執行錯誤如下面的示例 output msg 所示。 下面還顯示了示例代碼片段

代碼片段:

testStr = "cat tst.txt | grep Location | sed -e '/.*Location: //g' "
print "testStr = "+testStr
testStrOut = subprocess.Popen([testStr],shell=True,stdout=subprocess.PIPE).communicate()[0]

Output:

testStr = cat tst.txt | grep Location | sed -e '/.*Location: //g' 
cat: tst.txt: No such file or directory
sed: -e expression #1, char 15: unknown command: `/'

是否有可以使用的解決方法或 function?

感謝您的幫助 謝謝

我想您的主要錯誤與 python 無關。 更准確地說,有3個:

  1. 您忘記import subprocess
  2. 它應該是sed -e 's/.*Location: //g' 你寫了///g而不是s///g
  3. tst.txt不存在。

您應該將 testStr 作為第一個參數直接傳遞,而不是將其包含在列表中。 請參閱subprocess.Popen ,以“在 Unix 上,shell=True: ...”開頭的段落。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM