使用子进程检查文件的记录计数



如果文件只有一行,则发送错误消息。我使用的是Python 2.6.9版本。下面是我的代码。我得到了行数,但如果条件不起作用。

import os
import subprocess
count=subprocess.Popen('wc -l <20170622.txt', shell=True, stdout=subprocess.PIPE)
if count.communicate() == 1: 
    sys.exit("File has no data - 20170622.txt")

我尝试了不同的方法来使if条件起作用,但没有运气。在这里我想检查文件是否有多行.如果它没有超过一行,那么我必须发送错误消息。

from subprocess import Popen, PIPE
count = Popen("wc -l <20170622.txt", shell=True, stdout=PIPE)
if count.wait() == 0:                        # 0 means success here
    rows = int(count.communicate()[0])       # (stdout, stderr)[0]
    if rows == 1:                            # only one row
        # do something...       
else: 
    print("failed")                          # assume anything else to be failure

Popen 在成功时返回 0,因此首先我们必须检查命令是否成功运行:count.wait() --wait 直到进程完成并返回其退出代码。

如前所述,process.communicate()返回一个元组。您感兴趣的部分是第一部分,因为它包含标准输出。此外,通常最好不要在Popen中使用shell=True。可以使用打开的文件描述符作为标准来重写它。这给了你一个程序,比如(使用 Python 3(:

import sys
from subprocess import Popen, PIPE
input_file = '20170622.txt'
myinput = open(input_file)
with open(input_file, 'r') as myinput, Popen(['wc', '-l'], stdin = myinput, stdout=PIPE) as count:
    mystdout, mystderr = count.communicate()
    lines = int(mystdout.strip())
    print(lines)
    if lines <= 1: 
        sys.exit("File has no data - {}".format(input_file))

最新更新