file2.txt 用-6ren">
gpt4 book ai didi

python - 在 python 子进程 popen 中格式化命令

转载 作者:太空宇宙 更新时间:2023-11-03 17:59:22 24 4
gpt4 key购买 nike

我正在尝试格式化以下 awk 命令

awk -v OFS="\t" '{printf "chr%s\t%s\t%s\n", $1, $2-1, $2}' file1.txt > file2.txt

用于 python 子进程 popen。但是我很难格式化它。我已经尝试过类似答案中建议的解决方案,但没有一个有效。我也尝试过使用原始字符串文字。另外我不想使用 shell=True 因为不推荐这样做

根据评论进行编辑:我尝试过的命令是

awk_command = """awk -v OFS="\t" '{printf "chr%s\t%s\t%s\n", $1, $2-1, $2}' file1.txt > file2.txt"""
command_execute = Popen(shlex.split(awk_command))

但是执行此操作时出现以下错误

KeyError: 'printf "chr%s\t%s\t%s\n", $1, $2-1, $2'

谷歌搜索错误表明,当为未定义的键请求值但我不理解其上下文时会发生这种情况

最佳答案

> 是 shell 重定向运算符。要在 Python 中实现它,请使用 stdout 参数:

#!/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)

为了避免启动单独的进程,您可以在纯 Python 中实现这个特定的 awk 命令。

关于python - 在 python 子进程 popen 中格式化命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27985888/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com