繁体   English   中英

Python:如何将一个非常复杂的长字符串格式化为 subprocess.run function?

[英]Python: how to format a long very complex string to subprocess.run function?

我需要从 Python 运行几个复杂的 bash 命令。 其中之一是:

top -n1 -b | awk -vtime="$(date +%Y-%m-%d-%T)" 'NR==7{printf("Time\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n",$1,$5,$6,$9,$10,$11,$NF)}' > ~/logs/perfmon.log

此命令使用top命令将 header 打印到文件中,并使用awk格式化字符串。

第二条命令查找名为process_name的进程,并不断用top命令将其性能记录到创建的文件中。 Python 中不等待该命令。

问题是命令本身包含双引号"和撇号' ,以及转义字符\t\n 。而且它是一个长字符串。

我尝试将命令字符串定义为f-string并将双\放在转义字符之前,我尝试使用r-string ,但没有成功。 header 行打印时在单词之间没有制表符,或者该命令被awk命令误解。

我在下面附上我的 function。 这两个命令都需要一些帮助:)

感谢您在此处发布之前检查解决方案。

def execute_performance_monitoring(sample_frequency: int = default_top_frequency) -> None:
today = datetime.today()
date = today.strftime('%Y-%m-%d-%H-%M')

process_name = "find_and_log_me"

logs_dir = Path(logs_path)
full_file_name = logs_dir / f'{process_name}_{date}.log'

print_header_command = (
    'top -n1 -b'
    ' | awk -vtime="$(date +%Y-%m-%d-%T)" \'NR==7{{printf("Time %s  %s  %s  %s  %s  %s  %s\\n",$1,$5,$6,$9,$10,$11,$NF)}}\''
    f' > {full_file_name}'
)

print_perfmon_command = (
    f'top -b -o +%CPU -d {sample_frequency}'
    '| awk -vtime="$(date +%m-%d-%Y-%T)" \'NR>8{{printf("%s %s  %s  %s  %s  %s  %s  %s\\n"'
    ',\'time,$1,$5,$6,$9,$10,$11,$NF)}}\''
    f' | grep --line-buffered {process_name} >> {full_file_name} &'
)

subprocess.run(print_header_command)
subprocess.run(
    print_perfmon_command,
    shell=True,
    stdin=None,
    stdout=None,
    stderr=None,
    close_fds=True,
)

经过多次尝试和几天都没有成功,我已将命令移至采用相关参数的 bash 脚本,Python 脚本执行验证工作,并使用参数CCE 调用 ZD574D4BB40C84861791A694A999 脚本

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM