1

Using python how can I make this happen?

python_shell$>  print myPhone.print_call_log()  |  grep 555

The only thing close that I've seen is using "ipython console", assigning output to a variable, and then using a .grep() function on that variable. This is not really what I'm after. I want pipes and grepping on anything in the output (including errors/info).

3
  • 2
    It's a mistake to use the Python interactive console as a long-term shell environment. Use it for testing Python statements; attempting to use it as a general purpose shell is inviting an endless series of frustrations like this. Commented May 22, 2014 at 6:06
  • Use re to do pattern match in python or write the log to a temp file to use grep. Commented May 22, 2014 at 6:11
  • ipython has way to handle grepping output from a shell/system command. Example post from ipython's documentation. I'm hoping someone has bent this ability to be easier to leverage, and not limited to the contents of the object. Commented May 22, 2014 at 6:40

2 Answers 2

2

Python's interactive REPL doesn't have grep, nor process pipelines, since it's not a Unix shell. You need to work with Python objects.

So, assuming the return value of myPhone.print_call_log is a sequence:

call_log_entries = myPhone.print_call_log()
entries_containing_555 = [
        entry for entry in call_log_entries
        if "555" in entry]
Sign up to request clarification or add additional context in comments.

1 Comment

I think 'myPhone.print_call_log()' is a '\n' separated string and can use split('\n') to convert it to a sequence.
0

What about something like this.

import subprocess
results = subprocess.check_output('cat /path/to/call_log.txt | grep 555', shell=True)
print(results)

Or:

import subprocess
string = myPhone.print_call_log().replace("\'","\\'")
results = subprocess.check_output('echo \''+string+'\' | grep 555', shell=True)
print(results)

It is hard to tell without knowing what the return type of myPhone.print_call_log(). Is it a generator, or does it return a list? Or a string?

Related Questions:

Docs:

Edit:

Based on comment by glglgl

Something like this might be more appropriate as written by glglgl:

2 Comments

Rather than results = subprocess.check_output('echo \''+myPhone.print_call_log()+'\' | grep 555', shell=True), a combination of stdin=stubprocess.PIPE and .communicate() would be more appropriate... but then, you can omit the subprocess altogether and perform the search on your own.
BTW, what do you do if there are any ' in your print_call_log() output? If you replace them by '\'', you should be fine. But "elegant" is not quite the right word for this...

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.