首页 > 解决方案 > 如何将shell命令中的变量分配给python脚本

问题描述

我正在尝试使用 slurm 中的数组运行批处理。我只知道从数组(文本文件)中提取变量的 shell 命令,但未能将其分配为 Python 变量。

我必须为 Python slurm 脚本分配一个变量。我使用 shell 命令从数组中提取值。但是在将其分配给变量时遇到错误。我使用了子进程、os.system 和 os.popen。或者有什么方法可以从文本文件中提取值以用作 Python 变量?

start_date = os.system('$(cat startdate.txt | sed -n ${SLURM_ARRAY_TASK_ID}p)')

start_date = subprocess.check_output("$(cat startdate.txt | sed -n ${SLURM_ARRAY_TASK_ID}p)", shell=True)

start_date = os.popen('$(cat startdate.txt | sed -n ${SLURM_ARRAY_TASK_ID}p)').read()


start_date = '07-24-2004'

标签: pythonarraysshellslurmos.system

解决方案


不要使用$(...). 这将执行命令,然后尝试执行命令的输出。您希望将输出发送回 python,而不是由 shell 重新执行。

start_date = subprocess.check_output("cat startdate.txt | sed -n ${SLURM_ARRAY_TASK_ID}p", shell=True)

推荐阅读