subprocess call of sed command giving error

2019-02-21 04:32发布

问题:

I have a text file which contains the following line

PIXEL_SCALE      1.0            # size of pixel in arc

To replace 1.0 in it with 0.3, I tried to use sed via subprocess.call from python script. Following sed regex command works perfectly from shell.

sed -i 's/^\(PIXEL_SCALE\s*\)\([0-9]*\.[0-9]*\)/\10.3/' filename.txt

But the equivalent subprocess.call command gives me the following error.

subprocess.call(['sed','-i',"'s/^\(PIXEL_SCALE\s*\)\([0-9]*\.[0-9]*\)/\10.3/'",'filename.txt'])

sed: -e expression #1, char 1: unknown command: `''

I tried converting the string to raw string by prefixing string with r and also tried .encode("UTF-8"). But they didn't have any effect. What could be going wrong here?

Thanks

回答1:

' quotes are delimiters used by the shell. As you do not use a shell, you don't need them around your regular expression:

subprocess.call(['sed','-i',r"s/^\(PIXEL_SCALE\s*\)\([0-9]*\.[0-9]*\)/\10.3/",'filename.txt'])
#                           ^^                                                             ^

In addition, I used a raw string (r"....") to prevent interpretation of the backslash-escaped sequences by python.



回答2:

subprocess.call("sed -i 's/^\(PIXEL_SCALE\s*\)\([0-9]*\.[0-9]*\)/\10.3/' filename.txt", shell=True)

that works



回答3:

's/(PIXEL_SCALE\s*)[0-9]+[0-9]+/\10.3/'