sed 命令的子进程调用给出错误 [英] subprocess call of sed command giving error

查看:64
本文介绍了sed 命令的子进程调用给出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含以下行的文本文件

I have a text file which contains the following line

PIXEL_SCALE      1.0            # size of pixel in arc

要将其中的 1.0 替换为 0.3,我尝试通过 python 脚本中的 subprocess.call 使用 sed.以下 sed regex 命令在 shell 中完美运行.

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

但是等效的 subprocess.call 命令给了我以下错误.

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: `''

我尝试通过在字符串前加上 r 来将字符串转换为原始字符串,还尝试了 .encode("UTF-8").但它们没有任何效果.这里可能出了什么问题?

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?

谢谢

推荐答案

' 引号是 shell 使用的分隔符.由于您不使用 shell,因此您的正则表达式不需要它们:

' 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'])
#                           ^^                                                             ^

此外,我使用了一个原始字符串 (r"....") 防止python解释反斜杠转义序列.

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

这篇关于sed 命令的子进程调用给出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆