Formatting a command in python subprocess popen

前端 未结 2 690
无人及你
无人及你 2020-12-07 00:00

I am trying to format the following awk command

awk -v OFS=\"\\t\" \'{printf \"chr%s\\t%s\\t%s\\n\", $1, $2-1, $2}\' file1.txt > file2.txt
2条回答
  •  北海茫月
    2020-12-07 00:42

    > is the shell redirection operator. To implement it in Python, use stdout parameter:

    #!/usr/bin/env python
    import shlex
    import subprocess
    
    cmd = r"""awk -v OFS="\t" '{printf "chr%s\t%s\t%s\n", $1, $2-1, $2}'"""
    with open('file2.txt', 'wb', 0) as output_file:
        subprocess.check_call(shlex.split(cmd) + ["file1.txt"], stdout=output_file)
    

    To avoid starting a separate process, you could implement this particular awk command in pure Python.

提交回复
热议问题