0

I am kind of new to 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

1
  • 1
    give subprocess the full path of the file "tst.txt". Commented May 26, 2011 at 9:45

2 Answers 2

1

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.
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks- That was one mistake. Found it in the mean time. Also the following link answered to the question on escaping '\r' stackoverflow.com/questions/4392176/escape-for-str-in-python.
1

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: ...".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.