开发者

Escaping escape sequence in Python

开发者 https://www.devze.com 2023-03-08 17:24 出处:网络
I am kind of new to 开发者_JS百科python. Goal is to execute a shell command using subprocess parse & retrive the printed output from shell. The execution errors out as shown in the sample output m

I am kind of new to 开发者_JS百科python. Goal is to execute a shell command using subprocess parse & retrive the printed output from shell. The execution errors out as shown in the sample output msg below. Also shown below is the sample code snippet

Code snippet:

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: `/'

Is there a workaround or a function that could be used ?

Appreciate your help Thanks


I suppose your main error is not python related. To be more precise, there are 3 of them:

  1. You forgot to import subprocess.
  2. It should be sed -e 's/.*Location: //g'. You wrote ///g instead of s///g.
  3. tst.txt does not exist.


You should be passing testStr directly as the first argument, rather than enclosing it in a list. See subprocess.Popen, the paragraph that starts "On Unix, with shell=True: ...".

0

精彩评论

暂无评论...
验证码 换一张
取 消