【问题标题】:Rewrite shell script with GNU Parallel to Python [duplicate]使用 GNU Parallel to Python 重写 shell 脚本 [重复]
【发布时间】:2021-10-09 10:59:23
【问题描述】:

我有一个使用 GNU Parallel 并行运行函数的 shell 脚本。现在,我正在将脚本重写为 Python,但我不知道如何正确执行此操作。

在脚本中,我有:

parallel --jobs 5 --linebuffer run {1} ::: "${files[@]}"

如何将其转换为 Python 代码?在shell中,files是一个文件数组,run方法调用处理文件的外部程序。

在 Python 中,我有方法 def run(file),它有几个 Python 命令来准备数据,最后,它用 os.command 调用外部程序。

def run(file):
  do something with input file
  os.command(...)

【问题讨论】:

  • @mkrieger1 不完全正确。我不想使用Popen。我在python中有run方法,这个方法里面是os.command。线程似乎更合理,但我不知道是使用它还是多处理。另外,我不知道,传递文件数组很热。
  • 你为什么不想使用Popen?
  • 如何使用 Popen 调用 Python 方法?
  • 请注意,无论如何都会使用os.command 调用来创建进程。使用 Popen 创建用于调用内部 Python 方法的进程并不是很好,因为它通常太低级。使用processing pools (eg with map) 通常更简单更好。如果您知道您的处理是 IO 绑定并用 Python 编写的,那么线程会更好(由于 GIL)。

标签: python bash parallel-processing gnu-parallel


【解决方案1】:

我会使用多处理:

from multiprocessing import Pool

def run(file):
  do something with input file
  os.command(...)

if __name__ == '__main__':
  with Pool(5) as p:
    p.map(run, sys.argv[1:])

调用它:

python test.py "${files[@]}"

【讨论】:

    猜你喜欢
    • 2019-10-31
    • 2015-09-01
    • 1970-01-01
    • 2016-03-13
    • 2018-02-19
    • 2014-06-11
    • 2015-11-12
    • 2012-08-30
    • 1970-01-01
    相关资源
    最近更新 更多