Python 使用子流程检查文件中的记录计数

Python 使用子流程检查文件中的记录计数,python,subprocess,Python,Subprocess,若文件只有一行,则发送错误消息。我使用的是Python2.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")

若文件只有一行,则发送错误消息。我使用的是Python2.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")
导入操作系统
导入子流程
count=subprocess.Popen('wc-l
from subprocess import Popen,PIPE

count=Popen(“wc-l如上所述,
process.communicate()
返回一个元组。您感兴趣的部分是第一部分,因为它包含stdout。此外,通常最好不要在
Popen
中使用
shell=True
。可以使用打开的文件描述符作为stdin来重写它。这将为您提供一个类似(使用Python 3)的程序:

导入系统 从子流程导入Popen、PIPE 输入_文件='20170622.txt' myinput=打开(输入文件) 以open(input_file,'r')作为myinput,Popen(['wc','-l'],stdin=myinput,stdout=PIPE)作为计数: mystdout,mystderr=count.communicate() lines=int(mystdout.strip()) 打印(行)
这里是否需要行子流程?if len(open(filename).readlines()有什么问题>1:
?除了在打开文件后不关闭它之外,也就是说。@Kevin如果你仔细想想,wc比在内存中打开一个大文件并创建一个内容列表要快得多,重点放在大文件上。谢谢Kevin,它成功了。@Coldspeed我想知道我在使用子进程时犯了什么错误。谢谢你抓住了这一点错了。谢谢你,约翰。
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
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))