首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用shell()执行多个shell命令的推荐方法

使用shell()执行多个shell命令的推荐方法
EN

Stack Overflow用户
提问于 2017-08-08 02:44:52
回答 2查看 8.3K关注 0票数 19

在snakemake中,使用shell()函数执行多个命令的推荐方式是什么?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-08-08 07:35:49

您可以在规则的run块中多次调用shell() (规则可以指定run:而不是shell:):

代码语言:javascript
复制
rule processing_step:
    input:
        # [...]
    output:
        # [...]
    run:
        shell("somecommand {input} > tempfile")
        shell("othercommand tempfile {output}")

否则,由于run块接受Python代码,您可以构建一个字符串形式的命令列表并迭代它们:

代码语言:javascript
复制
rule processing_step:
    input:
        # [...]
    output:
        # [...]
    run:
        commands = [
            "somecommand {input} > tempfile",
            "othercommand tempfile {output}"
        ]
        for c in commands:
            shell(c)

如果在执行规则的过程中不需要Python代码,那么可以在shell块中使用带三重引号的字符串,并像在shell脚本中一样编写命令。对于纯shell规则来说,这无疑是最具可读性的:

代码语言:javascript
复制
rule processing_step:
    input:
        # [...]
    output:
        # [...]
    shell:
        """
        somecommand {input} > tempfile
        othercommand tempfile {output}
        """

如果shell命令依赖于前面命令的成功/失败,则可以使用||&&等常用的shell脚本操作符将它们连接起来

代码语言:javascript
复制
rule processing_step:
    input:
        # [...]
    output:
        # [...]
    shell:
        "command_one && echo 'command_one worked' || echo 'command_one failed'"
票数 47
EN

Stack Overflow用户

发布于 2018-03-28 19:44:45

我想我应该加上这个例子。这可能不是对用户问题的直接回答,但我在搜索类似的东西并试图弄清楚如何运行多个shell命令并在特定目录中运行其中一些命令(由于各种原因)时遇到了这个问题。

为了保持整洁,您可以使用shell脚本。

假设我有一个外壳脚本scripts/run_somecommand.sh,它执行以下操作:

代码语言:javascript
复制
#!/usr/bin/env sh
input=$(realpath $1)
output=$(realpath $2)
log=$(realpath $3)
sample="$4"

mkdir -p data/analysis/${sample}
cd data/analysis/${sample}
somecommand --input ${input} --output ${output} 2> ${log}

然后在你的Snakemake规则中,你可以这样做

代码语言:javascript
复制
rule somerule:
    input:
        "data/{sample}.fastq"
    output:
        "data/analysis/{sample}/{sample}_somecommand.json"
    log:
        "logs/somecommand_{sample}.log"
    shell:
        "scripts/run_somecommand.sh {input} {output} {log} {sample}"

注意:如果你在苹果电脑上工作,但没有realpath,你可以用brew install coreutils来安装,这是一个非常方便的命令。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45553762

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档