使用带有sed命令的os.system()时出现问题

2 python

我正在写一个小方法来替换文件中的一些文本.我需要的唯一参数是新文本,因为它总是与要替换的文件和文本相同.

当我尝试使用方法的参数时,我在使用os.system()调用时遇到问题

如果我使用如下所示的字符串,一切运行正常:

stringId = "GRRRRRRRRR"
cmd="sed '1,$s/MANAGER_ID=[0-9]*/MANAGER_ID=" + stringId + "/g' path/file.old > path/file.new"
os.system(cmd)
Run Code Online (Sandbox Code Playgroud)

现在,如果我尝试将字符串作为参数如下所示,则不执行该命令.我做了一个打印,看看命令是否正确,它是.如果我复制/粘贴到我的shell,我甚至可以成功执行它

import os
def updateExportConfigId(id):
stringId = "%s" % id
cmd= "sed '1,$s/MANAGER_ID=[0-9]*/MANAGER_ID=" + stringId + "/g' path/file.old > path/file.new"
print "command is " + cmd
os.system(cmd)
Run Code Online (Sandbox Code Playgroud)

有谁知道什么是错的?

谢谢

nos*_*klo 5

必须:不要使用os.system - 使用subprocess模块:

import subprocess

def updateExportConfigId(m_id, source='path/file.old', 
                             destination='path/file.new'):
    if isinstance(m_id, unicode):
        m_id = m_id.encode('utf-8')
    cmd= [
          "sed",
          ",$s/MANAGER_ID=[0-9]*/MANAGER_ID=%s/g" % m_id,  
          source,
         ]
    subprocess.call(cmd, stdout=open(destination, 'w'))
Run Code Online (Sandbox Code Playgroud)

使用此代码,您可以传递经理ID,它可以有空格,引用字符等.文件名也可以传递给函数,也可以包含空格和其他一些特殊字符.这是因为你的shell没有被不必要地调用,所以在你的操作系统上启动了一个较少的进程,你不必担心转义特殊的shell字符.

另一种选择:不要启动sed.使用python的re模块.

import re
def updateExportConfigID(m_id, source, destination):
    if isinstance(m_id, unicode):
        m_id = m_id.encode('utf-8')
    for line in source:
        new_line = re.sub(r'MANAGER_ID=\d*', 
                          r'MANAGER_ID=' + re.escape(m_id), 
                          line)
        destination.write(new_line)
Run Code Online (Sandbox Code Playgroud)

并称之为:

updateExportConfigID('GRRRR', open('path/file.old'), open('path/file.new', 'w'))
Run Code Online (Sandbox Code Playgroud)

无需新的流程.