Best way to rewrite Popen

Cecil Westerhof Cecil at decebal.nl
Tue May 19 16:19:51 EDT 2015


Op Tuesday 19 May 2015 21:13 CEST schreef Cecil Westerhof:

> Op Tuesday 19 May 2015 19:36 CEST schreef Jon Ribbens:
>
>> On 2015-05-19, Cecil Westerhof <Cecil at decebal.nl> wrote:
>>> At the moment I am playing with things like: p =
>>> subprocess.Popen('ls -l', shell = True, stdout = subprocess.PIPE)
>>>
>>> I think that most of the times this are the values I want. So it
>>> would be nice to overrule the defaults. What is the best way to do
>>> this? So creating a function that is exactly the same except for
>>> the defaults for shell and stdout (and maybe stderr).
>>
>> Yes.
>>
>> def shellprocess(cmd, **kwargs):
>> return subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
>> **kwargs)
>
> Will that not go wrong if I call it with?
> shellprocess('ls -1', shell = False)
>
>
>>> It is a little less important as I first thought, because I found
>>> the following: error, output = subprocess.getstatusoutput('ls -1')
>>> files_new = output.splitlines() But it is still nice to know.
>>
>> Why are you doing this anyway, rather than using os.listdir()?
>> Invoking subprocesses via the shell is very rarely a good idea.
>
> I want to rewrite a Bash script into a Python script. The 'ls -1' is
> only an example. But Popen and listdir give a different output. The
> sorting is different. But I could sort it myself.
>
> Another problem is that I work with a filter later on. But I could
> do that with Python also of-course. So maybe I should rethink what I
> want to do. ;-)

It looks like that this does what I want (the dot is needed so that it
also works with 2.7):
    files = sorted(os.listdir('.'))
    p = re.compile('actions-2015-05-[0-9][0-9].sql$')
    current_month = [ file for file in files if p.match(file) ]

-- 
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof



More information about the Python-list mailing list