Best way to rewrite Popen

Jon Ribbens jon+usenet at unequivocal.co.uk
Tue May 19 16:14:50 EDT 2015


On 2015-05-19, Cecil Westerhof <Cecil at decebal.nl> wrote:
> 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)

Yes. I thought you wanted a function that was specific to your
purpose, rather than one that was identical to Popen but with
different defaults. For that I suppose you could do:

  def shellprocess(args, **kwargs):
      kwargs.setdefault("shell", True)
      kwargs.setdefault("stdout", subprocess.PIPE)
      return subprocess.Popen(args, **kwargs)

> 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. ;-)

Indeed, porting a script from bash to Python is probably best done by
writing the identical functionality in the style of Python, rather
than doing a line-by-line literal conversion.



More information about the Python-list mailing list