【问题标题】:How do I specify the number of CPU cores to use within a python script running via bash script?如何指定在通过 bash 脚本运行的 python 脚本中使用的 CPU 内核数?
【发布时间】:2019-09-30 11:51:49
【问题描述】:

我想将一些 fasta 文件与基因组对齐,为了快速做到这一点,我有一个 python 脚本,它遍历一个目录以仅选择某些文件。我使用了子进程,如果我没有在循环中运行它,我已经包含了我本来可以放在基本 bash 脚本中的所有内容。问题是我想并行运行它,但是在子进程中使用 $NSLOTS 不起作用。

我的 bash 脚本是这样的:

#!/bin/bash --login
#$ -cwd
#$ -pe smp.pe 8 #specifies to use 8 cores

module load apps/binapps/anaconda3/2019.03  #Python 3.7.3
module load apps/bioinf
module load apps/star/2.5.3a/gcc-4.8.5

python STAR_aligner.py

我的python脚本是这样的:

import subprocess
import os

directory = '/mnt/fls01-home01/mfbx3sgh/scratch/Trimming'
genome_idx = '/mnt/fls01-home01/mfbx3sgh/scratch/Genome_Index'
genome_dir = '/mnt/fls01-home01/mfbx3sgh/scratch/Genome/'

file_list = os.listdir(directory)

for read_1 in file_list:

    if 'paired' in read_1:

        if '_1_' in read_1:

            read_2 = read_1.replace('_1_', '_2_')

            subprocess.run(['STAR', '--runThreadN', '$NSLOTS', '--genomeDir', genome_idx, '--readFilesIn', read_1,
                            read_2, '--readFilesCommand', 'gunzip', '-c', '--outFileNamePrefix', genome_dir])

如您所见,我在 bash 脚本中指定使用 8 个内核,然后在子进程位中调用 $NSLOTS,当不在 python 脚本中时,它可以使用指定的内核。

我得到的错误是

EXITING: fatal input ERROR: runThreadN must be >0, user-defined runThreadN=0

Sep 30 11:52:24 ...... FATAL ERROR, exiting

【问题讨论】:

  • 什么是NSLOTS?它设置在某个地方吗?

标签: python python-3.x bash parallel-processing subprocess


【解决方案1】:

Python 脚本似乎根本没有添加任何价值,您应该将其全部编写为 Bash 脚本。

#!/bin/bash
root="/mnt/fls01-home01/mfbx3sgh/scratch"
for read_1 in "$root/Trimming/"*; do
    case $read_1 in
     *paired*_1_*|*_1_*paired*)
        STAR --runThreadN "$NSLOTS" --genomeDir "$root/Genome_Index/" \
          --readFilesIn "$read_1" "${read_1//_1_/_2_}" \
          --readFilesCommand gunzip -c --outFileNamePrefix "$root/Genome/" ;;
    esac
done

如果您的问题是如何在 Python 中正确使用 $NSLOTS,那将是

os.environ['NSLOTS']

(字符串'$NSLOTS'只是静态字符串$NS等)

【讨论】:

  • 我猜"gunzip -c" 应该作为单个参数引用?在 Python 中的表达方式很简单,就是'gunzip -c'
  • 谢谢三人组!非常有用的答案,我是使用 bash 的新手,所以这就是我使用 python 循环的原因,但是你的 bash 建议让一切变得更容易并且正在工作
猜你喜欢
  • 1970-01-01
  • 2022-01-05
  • 2017-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-01
  • 1970-01-01
相关资源
最近更新 更多