【问题标题】:Python - using subprocess to call sed?Python - 使用子进程调用 sed?
【发布时间】:2011-10-06 02:57:48
【问题描述】:

我希望使用子进程从 python 调用 sed。我尝试使用的脚本如下。但是,这会将 sed 输出通过管道传输到标准终端。在我的 subprocess.call 语句中似乎无法识别“>”运算符。有什么建议?

import sys 
import os 
import subprocess

files = os.listdir(sys.argv[1])

count = 0

for f in files:
    count += 1
    inp = sys.argv[1] + f
    outp = '../' + str(count) + '.txt'
    sub = subprocess.call(['sed', 's/\"//g', inp, '>', outp])

另外 - 我的文件名中有空格,即“file1 .txt”。这可能是问题吗?当我从终端调用 sed 时,我的 sed 命令可以正常工作,而不是从脚本调用。

谢谢。

【问题讨论】:

  • 有什么理由不在 Python 中这样做?
  • @robert +1 这是一个很好的观点,你应该提供它,包括解决方案,作为答案。

标签: python sed subprocess


【解决方案1】:

使用

out_file = open(outp, "w")
sub = subprocess.call(['sed', 's/\"//g', inp], stdout=out_file )

【讨论】:

  • @robert,我今天还没喝咖啡,但我没有看到任何空间?
  • 这是有道理的。谢谢! D :-)
【解决方案2】:

跳过运行所有 sed 进程而只用 Python 完成工作会快得多

import os
import sys
files = os.listdir(sys.argv[1])

for count, f in enumerate(files):
    with open( os.path.join(sys.argv[1],f), "r" ) as source:
        with open( os.path.join('..',str(count)+'.txt'), "w" ) as target:
            data= source.read()
            changed= source.replace('"','')
            target.write( changed )

这会运行得更快,因为它不会派生很多子进程。

【讨论】:

  • 我认为应该改为changed = data.replace('"','')。对吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-27
  • 1970-01-01
  • 1970-01-01
  • 2011-11-01
  • 2019-04-29
  • 2013-11-15
  • 2018-12-16
相关资源
最近更新 更多