用subprocess.check_output调用的sed返回\ x01 \ n

时间:2018-09-26 01:09:36

标签: python

我有一个要运行的数据文件。 下面给出了test.data文件的简化版本

test.data
=============
some text SEARCH_URL = "google.com" some ending text

我想从中提取没有引号的SEARCH_URL。 以下sed命令在bash提示符下效果很好

sed -n 's/^.*SEARCH_URL.*\"\(.*\)\".*/\1/p' ./test.data

Output
=============
google.com

但是从带check_output的python脚本中调用时,该命令不起作用。我得到的唯一输出是一个神秘的字符串“ \ x01 \ n”

geturl.py
=============
import subprocess
import re

#sed -n 's/^.*SEARCH_URL.*\"\(.*\)\".*/\1/p' test.data #works in bash

res = subprocess.check_output(["sed", "-n", 's/^.*SEARCH_URL.*\"\(.*\)\".*/\1/p', "test.data"]) print("Search URL is : ", res)

这将输出打印为

python geturl.py
('Search URL is : ', '\x01\n')

我想念什么?

1 个答案:

答案 0 :(得分:1)

当您希望字符串文字中的每个反斜杠表示文字反斜杠时,应使用raw string。否则,您的\1字符串中的's/^.*SEARCH_URL.*\"\(.*\)\".*/\1/p'将被解释为序号为1的字符,即'\x01

更改:

res = subprocess.check_output(["sed", "-n", 's/^.*SEARCH_URL.*\"\(.*\)\".*/\1/p', "test.data"])

收件人:

res = subprocess.check_output(["sed", "-n", r's/^.*SEARCH_URL.*\"\(.*\)\".*/\1/p', "test.data"])