Using sh library with grep command

Luca Fabbri luca at keul.it
Sat Nov 23 12:23:12 EST 2013


On Sat, Nov 23, 2013 at 5:29 PM, Peter Otten <__peter__ at web.de> wrote:
> Luca wrote:
>
>> I'm trying to use sh (https://pypi.python.org/pypi/sh) for calling
>> system grep command but it's now working as expected.
>>
>> An example:
>>
>>     import sh
>>     sh.grep('abc', os.getcwd(), '-r')
>>
>> But I get the ErrorReturnCode_1: exception, that I learned is the
>> normal exit code for grep command when it not found any match.
>>
>> The error instance object reported that the command run is:
>>
>>     *** ErrorReturnCode_1:
>>       RAN: '/usr/bin/grep abc /Users/keul/test_sh'
>>
>> Obviously manually running the command I get some output and exit code 0.
>>
>> Where I'm wrong?
>
> Did you run grep with or without the -r option?
>
> The code sample and the error message don't match. Maybe you accidentally
> left out the -r in your actual code.
>

Sorry all, it was a stupid error and I provided a bad example.

I was running...
   sh.grep('"abc"', os.getcwd(), '-r')

...and the output of the command inside the exception was exactly...
    RAN: '/usr/bin/grep "abc" /Users/keul/test_sh -r'

So, at first glance it was ok (copying/pasting it in in the terminal
return exactly was I expected).

The error? The doublequote inclusion.

Using this...
   sh.grep('abc', os.getcwd(), '-r')

...I  get this output...
    RAN: '/usr/bin/grep abc /Users/keul/test_sh -r'

But this time I get the expected result (both in terminal and python
env). So seems that when quoting you get a false positive right
command output but a wrong execution.


-- 
-- luca

twitter: http://twitter.com/keul
linkedin: http://linkedin.com/in/lucafbb
blog: http://blog.keul.it/



More information about the Python-list mailing list