代码之家  ›  专栏  ›  技术社区  ›  Artem Sokolov

正在将值通道写入文件

  •  0
  • Artem Sokolov  · 技术社区  · 3 年前

    将值从通道写入文件的最佳方式是什么?

    考虑以下示例:

    nextflow.enable.dsl=2
    
    workflow {
    
        ch = Channel.of('a', 'b', 'c')
    
        file('test.txt').withWriter {out -> 
            out.println "My values are:"
            ch.subscribe {
                out.println "$it"
                println "$it"
            }
        }
    }
    

    这将正确输出 a , b , c 到stdout,但是 test.txt 将只包含 My values are: 什么都没有。清晰地 .subscribe{} 正在对值进行迭代(否则它将不会向stdout显示这些值),并且正在对文件进行写入(否则文件将不会 我的价值观是: ),但为什么它不将值写入文件?

    0 回复  |  直到 3 年前
        1
  •  1
  •   Steve    3 年前

    通常的方法是使用 collectFile 操作员: https://nextflow-io.github.io/patterns/collect-into-file/

    如果您不需要排序输出,并且希望在发出条目时附加条目,您也可以使用 sort: false 禁用内容排序和 concat 运算符来准备页眉:

    workflow {
    
        my_header = Channel.value( "My values are:" )
        my_values = Channel.of( 'foo', 'bar', 'baz' )
        
        my_header
            .concat( my_values )
            .collectFile( name: 'test.txt', newLine: true, sort: false )
            .view()
    
    }
    

    结果:

    $ nextflow run main.nf 
    N E X T F L O W  ~  version 23.04.1
    Launching `main.nf` [marvelous_marconi] DSL2 - revision: c9242fbc73
    /path/to/work/tmp/ea/d8ec4488443faf816cb6a213f3bad7/test.txt
    

    的内容 /path/to/work/tmp/ea/d8ec4488443faf816cb6a213f3bad7/test.txt 以下为:

    My values are:
    foo
    bar
    baz
    

    请注意,您也可以使用闭包来写入文件,例如:

    workflow {
    
        def test_file = new File( 'test.txt' )
        def write_value = { value ->
            test_file << value + "\n"
        }
    
        my_values = Channel.of( 'foo', 'bar', 'baz' )
    
        Channel
            .value( "My values are:" )
            .concat( my_values )
            .subscribe { write_value(it) }
    }
    
    $ cat test.txt 
    My values are:
    foo
    bar
    baz
    
        2
  •  1
  •   Artem Sokolov    3 年前

    以下似乎是实现所需行为的变通方法:

    nextflow.enable.dsl=2
    
    workflow {
        Channel.of('a', 'b', 'c')
            .map{ it ->
                "My values are:\n$it\n"
            }
            .collectFile(
                name: 'test.txt',
                storeDir:'.',
                keepHeader: true,
                skip: 1
            )
    }
    

    解决方法包括为每个元素准备标题,允许 .collectFile() 。 输出文件将包含:

    My values are:
    a
    c
    b
    
    推荐文章