【问题标题】:Processing 2 folders simultaneously同时处理2个文件夹
【发布时间】:2015-04-10 14:21:55
【问题描述】:

我正在使用 C shell 脚本。我有 2 个目录名称 dir1 和 dir2 并且都包含 n 个文件。我必须同时处理这些文件。让我解释一下:我有一个命令可以进行一些处理并给出输出。例如。

 score = custom_command (file from dir1 , file from dir2) 

我需要将其作为批处理来执行。如何编写脚本来执行此操作?

这是我所做的(算法),但它不起作用:我认为这是一个逻辑缺陷。 也欢迎在 python 语言中提供任何帮助,我想知道我们没有通过多个目录读取文件的功能。

foreach filename1 in dir1
  cd dir2
  foreach filename2 in dir2
    cd -
    score = custom_command ($filename1 , $filename2)
  end
end

【问题讨论】:

  • 你使用的是bash还是csh
  • 使用 csh 但任何算法也可以。
  • 在 bash 中很确定你可以做类似for i in /dir1/*;do score=custom_command(dir1/${i##*/},dir2/${i##*/});done 的事情。您的命令也不会针对两个目录中的每个文件对每个文件执行自定义命令,而不仅仅是对应的文件。
  • s 在 Python 中,我也可以为此目的使用 python。如果可能的话,建议在 python lang 中使用一些解决方案。
  • 人们要求澄清他们的答案,但只是为了做到这一点:您是否尝试进行 N^2 处理(dir1 中的每个 n 个文件与 dir2 中的每个 n 个文件)或者是存在相关性,因此您拥有完全相同的文件(具有不同的数据),因此只执行 n 个处理步骤(dir1 中的 n 个文件中的每一个仅针对 dir2 中的相应文件)?

标签: python csh


【解决方案1】:

您想同时运行 N^2 个进程吗?尝试(在 bourne shell 中):

for f1 in /p/a/t/h/dir1/*; do for f2 in /p/a/t/h/dir2/*; do cmd $f1 $f2& done; done

停止使用 csh! (我假设您的评论“使用 csh 但任何算法也可以工作”的意思是“任何语言都可以工作”。)

【讨论】:

  • 在 Python 中,我也可以为此目的使用 python。如果可能的话,建议在 python lang 中使用一些解决方案。
【解决方案2】:

以下是您在 Python 中描述的一种方法:

import os
import itertools

dir1='/tmp/x'
dir2='/tmp/z'

files1 = [os.path.join(dir1,x) for x in sorted(os.listdir(dir1))]
files2 = [os.path.join(dir2,x) for x in sorted(os.listdir(dir2))]

def custom_command(file1, file2):
    # Some custom code goes here,
    #   for example, this meaningless drivel
    return os.path.getsize(file1)*os.path.getsize(file2)

for file1, file2 in itertools.product(files1, files2):
    score = custom_command(file1, file2)
    print file1, file2, score

或者,

import os
import itertools

dir1 = '/tmp/x'
dir2 = '/tmp/z'

def custom_command(file1, file2):
    # Some custom code goes here,
    #   for example, this meaningless drivel
    return os.path.getsize(file1)*os.path.getsize(file2)

for file1 in os.listdir(dir1):
    for file2 in os.listdir(dir2):
        file1 = os.path.join(dir1, file1)
        file2 = os.path.join(dir2, file2)
        score = custom_command(file1, file2)
        print file1, file2, score

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-27
    • 1970-01-01
    • 2023-02-01
    • 2021-06-30
    • 2018-11-19
    • 1970-01-01
    相关资源
    最近更新 更多