【问题标题】:subprocess.call with sed pass variable带有 sed 传递变量的 subprocess.call
【发布时间】:2017-02-27 09:41:54
【问题描述】:

我正在尝试使用subprocess.call 运行 Python 脚本以在匹配模式后添加一行。方法如下:

addline1 是可变的,其值为 "hello world1"

filename1 是包含路径和文件名的变量,例如"/tmp/path1/filename.conf"

filename.conf 中,它有大约35 行,我想在匹配字符串"ReWriteEngine On" 之后插入一行

subprocess.call(["sed","-i" ,'/ReWriteEngine On/a', addline1,filename])

它失败并出现以下异常:

**sed: -e expression #1, char 16: expected \ after `a', `c' or `i'**

任何人都可以建议进行任何更正吗?


代码尝试使用fileinput 而不是sed

import fileinput
processing_foo1s = False
for line in fileinput.input('/tmp/filename1/mod_wl_ohs.conf', inplace=1):
    if line.startswith("RewriteEngine On"):
        processing_foo1s = True
    else:
        if processing_foo1s:
            print 'foo bar'
            processing_foo1s = False
            print line

【问题讨论】:

  • 为什么不用python本身来做这一切呢?
  • 用 python 本身?你能详细说明一下吗?你的意思是使用 os.system 调用?
  • 我什至在 python 本身中尝试过这种方式,这对添加新字符串没有帮助: import fileinput processing_foo1s = False for line in fileinput.input('/tmp/filename1/mod_wl_ohs.conf', inplace =1): if line.startswith("RewriteEngine On"): processing_foo1s = True else: if processing_foo1s: print 'foo bar' processing_foo1s = False print line,
  • 关于sed的问题,可以通过构造字符串并传递给子进程来解决。例如:sed_cmd = '/ReWriteEngine On/a' + addline1subprocess.call(['sed', '-i', sed_cmd, filename1])
  • 当然——让我试试看。

标签: python sed subprocess


【解决方案1】:

更正sed 问题:

sed_cmd = '/ReWriteEngine On/a' + addline1
subprocess.call(['sed', '-i', sed_cmd, filename1])

注意:如果字符串必须在行首匹配,请使用/^ReWriteEngine On/a


fileinput

import fileinput
for line in fileinput.input(filename1, inplace=1):
    print line,
    if line.startswith("ReWriteEngine On"):
        print 'foo bar'

参考:Python: Prevent fileinput from adding newline characters

【讨论】:

    猜你喜欢
    • 2018-08-19
    • 1970-01-01
    • 2019-02-16
    • 2017-08-06
    • 2017-12-15
    • 2020-06-20
    • 2012-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多