Python - 使用子进程调用 sed? [英] Python - using subprocess to call sed?

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

问题描述

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

I wish to call sed from python using subprocess. The script I tried using is below. however, this pipes the sed output to the standard terminal. It seems that the '>' operator is not recognised from within my subprocess.call statement. Any suggestions?

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 命令工作正常,而不是从脚本中调用.

Also - my file names have spaces in them, i.e., " file1 .txt". Could this be the issue? My sed command works fine when I call sed from the terminal, just not from the script.

谢谢.

推荐答案

使用

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

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

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