あなたのコマンドの何が問題なのかわかりません。とにかく、 subprocess.call()関数を使用すると確実に良くなります。次のファイルがあるとします。
$ cat test.txt
abc
def
ここで、次のプログラムを実行すると:
import subprocess
oldstr = 'a'
newstr = 'AAA'
path = 'test.txt'
subprocess.call(['sed', '-i', 's/'+oldstr+'/'+newstr+'/', path])
これを取得します:
$ cat test.txt
AAAbc
def
また、oldstr
/newstr
の中にスラッシュ ( /
) がある場合、コマンドも壊れます。スラッシュをエスケープされたスラッシュに置き換えることで解決できます。
>>> print 'my/string'.replace('/', '\\/')
my\/string
したがって、このファイルがある場合:
$ cat test.txt
this is a line and/or a test
this is also a line and/or a test
を置き換えたい場合and/or
は、変数のスラッシュを適宜置き換えます。
import subprocess
oldstr = 'and/or'
newstr = 'AND'
path = 'test.txt'
subprocess.call(['sed', '-i', 's/'+oldstr.replace('/', '\\/')+'/'+newstr.replace('/', '\\/')+'/', path])
もちろん、もう少し読みやすくすることもできます。
import subprocess
oldstr = 'and/or'
newstr = 'AND'
path = 'test.txt'
sedcmd = 's/%s/%s/' % (oldstr.replace('/', '\\/'), newstr.replace('/', '\\/'))
subprocess.call(['sed', '-i', sedcmd, path])