使用Python同时对文件夹中的多个文件运行perl脚本

问题描述 投票:0回答:1

这是我目前的 Perl 脚本:

#!/usr/bin/perl
use open qw/:std :utf8/;
use strict;
use warnings;

if (defined $ARGV[0]){
my $filename = $ARGV[0];
my %count;

open (my $fh, $filename) or die "Can't open '$filename' $!";
while (<$fh>)
{
        $count{ lc $1 }++ while /(\w+)/g;
}
close $fh;

my $array = 0;

foreach my $word ( sort { $count{$b} <=> $count{$a} } keys %count)
{
    print "$count{$word} $word\n" if $array++ < 10;
}

}else{
print "Please enter the name of the file: ";
my $filename = ($_ = <STDIN>);

my %count;

open (my $fh, $filename) or die "Can't open '$filename' $!";
while (<$fh>)
{
        $count{ lc $1 }++ while /(\w+)/g;
}
close $fh;

my $array = 0;

foreach my $word ( sort { $count{$b} <=> $count{$a} } keys %count)
{
    print "$count{$word} $word\n" if $array++ < 10;
}
}

这是我目前的 Python 脚本:

#!/usr/bin/env python3
import os

perlscript = "perl " + " perlscript.pl " + " /home/user/Desktop/data/*.txt " + " >> " + "/home/user/Desktop/results/output.txt"
os.system(perlscript)

问题:当数据文件夹中有多个txt文件时,脚本仅在一个文件上运行并忽略所有其他txt文件。有没有办法同时在所有 txt 文件上运行 perlscript?

另一个问题:我还尝试在执行后使用 os.remove 删除 txt 文件,但它们在 perlscript 有机会执行之前被删除。

有什么想法吗? :)

python perl
1个回答
3
投票

该 Perl 脚本处理一个文件。此外,通过

os.system
传递到 shell 的字符串不会按照
*
shell glob 的预期扩展为带有文件列表的有效命令。

相反,请使用

os.listdir
(或
os.scandir
)、
os.walk
glob.glob
在 Python 中构建文件列表。然后迭代该列表并在每个文件上调用该 Perl 脚本(如果它一次只能处理一个文件)。或者,修改 Perl 脚本以处理多个文件,然后对整个列表运行一次。

保留当前 Perl 脚本并在每个文件上运行它

import os

data_path   = "/home/user/Desktop/data/"
output_path = "/home/user/Desktop/result/"

for file in os.listdir(data_path):
    if not file.endswith(".txt"):
        continue

    print("Processing " + file)                      # better use subprocess
    run_perlscript = "perl " + " perlscript.pl " + \
        data_path + file  + " >> " + output_path + "output.txt"
    os.system(run_perlscript)

需要重写 Perl 脚本以删除不需要的重复代码。

但是,最好使用 subprocess 模块来运行和管理外部命令。即使在 os.system 文档本身中也建议这样做。 比如说

import subprocess

with open(output_path + "output.txt", "a") as fout:
    for file in os.listdir(path):
        if not file.endswith(".txt"):
            continue 
        subprocess.run(["perl", "script.pl", data_path + file], stdout=fout)

在问题的

"a"
重定向之后,文件以追加模式 (
>>
) 打开。

推荐的 subprocess.run 从 python 3.5 开始可用;否则使用Popen

另一个可以说是“正确”的选项是调整 Perl 脚本,以便它可以处理多个文件。然后你只需要运行一次,使用整个文件列表。

use strict;
use warnings;
use feature 'say';    
use open ':std', ':encoding(UTF-8)';

foreach my $filename (@ARGV) {
    say "Processing $filename";

    my %count;

    open my $fh, '<', $filename  or do {
       warn "Can't open '$filename': $!";
       next;
    };
    while (<$fh>) {   
        $count{ lc $1 }++ while /(\w+)/g;
    }   
    close $fh;

    my $prn_cnt = 0;
    foreach my $word ( sort { $count{$b} <=> $count{$a} } keys %count) {   
        print "$count{$word} $word\n" if $prn_cnt++ < 10; 
    }   
}

这会在文件上打印一条无法打开的警告,并跳到下一个文件。如果您希望脚本在任何意外文件上退出,请将

or do { ... };
替换为原始
die

然后,现在使用 glob.glob 作为示例

import glob
import subprocess

data_path   = "/home/user/Desktop/data/"
output_path = "/home/user/Desktop/result/"

files = glob.glob(data_path + "*.txt")

with open(output_path + "output.txt", "a") as fout:
    subprocess.run(["perl", "script.pl", files], stdout=fout)

由于这会将整个列表作为命令参数传递,因此它假设不存在(大量)数千个文件,从而超出管道或命令行的某些长度限制。

© www.soinside.com 2019 - 2024. All rights reserved.