如何在python中将os.popen命令更改为子处理命令 [英] How change a os.popen command to subprocess command in python

查看:119
本文介绍了如何在python中将os.popen命令更改为子处理命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道os.popen现在已被弃用.因此,这是将os.popen命令转换为子进程的最简单方法.

I know that os.popen is deprecated now. So which is the easiest way to convert a os.popen command to subprocess.

cmd_i = os.popen('''sed -n /%s/,/%s/p %s | grep "Invalid Credentials"''' % (st_time, en_time, fileName))

推荐答案

subprocess代码将大致等效.

output = subprocess.check_output(
    '''sed -n /%s/,/%s/p %s | grep "Invalid Credentials"''' % (st_time, en_time, fileName),
    shell=True)

输出被捕获到一个变量中,而不是溢出到Python控制之外的标准输出中.如果您只想print,请继续执行该操作.

The output is captured into a variable, rather than spilled out onto standard output outside of Python's control. If all you want is to print it, go ahead and do that.

如果grep未找到任何内容,则将引发异常.如果您想以一种或另一种方式处理这种极端情况,可以使用except捕获它.

This will throw an exception if grep doesn't find anything. You can trap it with except if you want to handle this corner case one way or another.

但是,您可以轻松地用本地Python代码替换所有这些内容.

However, you could easily replace all of this with native Python code.

with open(fileName, 'r') as input:
    between = False
    output = []
    for line in input:
        if st_time in line:
            between = True
        if between and 'Invalid Credentials' in line:
            output.append(line)
        if en_time in line:
            between = False

在这种情况下,output是一个列表.每个捕获的行仍包含其终止的换行符. (当然,如果那不是您想要的,易于修复.)

The output in this case is a list. Every captured line still contains its terminating newline. (Easy to fix if that's not what you want, of course.)

作为一种优化,看到en_time时可以break(尽管该脚本与sed脚本并不完全等效).

As an optimization, you could break when you see en_time (though then the script won't be exactly equivalent to the sed script).

这也应该很容易适应st_time在日志文件中未完全出现的情况.您将需要解析每行上的时间戳,然后在解析的日期戳等于或大于(解析的)st_time值时简单地开始处理.同样,解析en_time并在看到带有等于或大于该值的时间戳的日志条目时退出.

This should also be easy to adapt to a scenario where st_time doesn't occur exactly in the log file. You will need to parse the time stamp on each line, and then simply start processing when the parsed date stamp is equal to or bigger than the (parsed) st_time value. Similarly, parse en_time and exit when you see log entries with time stamps equal to or above this value.

这篇关于如何在python中将os.popen命令更改为子处理命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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