Is there a Python equivalent to `perl -pi -e`? Is there a Python equivalent to `perl -pi -e`? python python

Is there a Python equivalent to `perl -pi -e`?


The command line usage from 'python -h' certainly strongly suggests there is no such equivalent. Perl tends to make extensive use of '$_' (your examples make implicit use of it), and I don't think Python supports any similar concept, thereby making Python equivalents of the Perl one-liners much harder.


An equivalent to -pi isn't that hard to write in Python.

  1. Write yourself a handy module with the -p and -i features you really like. Let's call it pypi.py.

  2. Use python -c 'import pypi; pypi.subs("this","that")'

You can implement the basic -p loop with the fileinput module.

You'd have a function, subs that implements the essential "-i" algorithm of opening a file, saving the backup copy, and doing the substitute on each line.

There are some activestate recipes like this. Here are some:

Not built-in. But not difficult to write. And once written easy to customize.


I know this is a couple of years too late, but I've recentlyfound a very nice tool called pyp, which doesexactly what you've asked for.

I think your command should be:

pyp "p.replace('foo','bar')"