【问题标题】:How to use Python to acquire auto run program如何使用Python获取自动运行程序
【发布时间】:2017-09-19 08:40:02
【问题描述】:

1。背景

  • 我现在正在使用大气模拟模型(名为 WRF)。该模型由其自己的控制文件 namelist.input

  • 控制
  • 当我想模拟一段时间内的大气情况时,只需在namelist.input中更改开始时间和结束时间,然后运行模型

    vim namelist.input ## Change the simulated period mpirun np -16 ./wrf.exe

2。我的尝试

当目标周期足够大(例如1年)时,较长的计算时间会降低结果的稳定性。 (可能有人熟悉蝴蝶效应:如果计算时间过长,即使模拟结果与现实相差很小,也会变得巨大)

所以,我需要将模拟周期分成几个子部分并多次运行模型。有一个研究人员编写的.csh 文件可以实现我的目标。我把它上传到这里作为参考。

#!/bin/csh -f

set year = "2013"


foreach strtime (010106010600 010512011100) ## just show two periods here
set smon = `echo ${strtime}|cut -c1-2`
set sday = `echo ${strtime}|cut -c3-4`
set shr  = `echo ${strtime}|cut -c5-6`
set emon = `echo ${strtime}|cut -c7-8`
set eday = `echo ${strtime}|cut -c9-10`
set ehr  = `echo ${strtime}|cut -c11-12`

cat > namelist.input << EOF
 start_year                          = ${year},${year},
 start_month                         = ${smon},${smon},
 start_day                           = ${sday},${sday},
 start_hour                          = ${shr},${shr},
 end_year                            = ${year},${year},
 end_month                           = ${emon},${emon},
 end_day                             = ${eday},${eday},
 end_hour                            = ${ehr},${ehr},
 ... # the .csh file contain all content of __namelist.input__ with start and end time changes.  

EOF

# running  wrf
 mpirun -np 16 ./wrf.exe
end

我想编写一个 Python 程序来替代 csh 文件。 Python语言更强大(我可以在同一个.py程序中对输出文件进行后处理)

3。我的问题

我曾多次尝试编写用于自动运行 WRF 模型的 .py 程序。它包含三个主要元素:

  • 将开始时间和对应的结束时间设置为列表,然后循环列表重新运行。

  • 使用不同的时间段更改 namelist.input

  • 在 python 环境中运行命令行程序。

     from subprocess import call
     call(["mpirun", "-np 16 ./wrf.exe"])    
    

但我对重新开始的时间点感到困惑。

言外之意,如何测试一次运行已经结束,我需要在 Python 中为下一个周期重新运行模型

【问题讨论】:

  • subprocess.call 不会返回,除非给定的命令(在本例中为 mpirun)完成。因此,您可以使用 for/while 循环重复调用 call 函数。能解释一下您的要求吗?
  • 也许我用错了subprocess.call。在终端中,我输入了mpirun xxx 来执行程序。我想在 Python 脚本中做同样的事情
  • 我试过os.system("mpirun xxx")。它工作正常。

标签: python linux python-2.7 command-line subprocess


【解决方案1】:

所以问题是:如何检查进程是否仍在运行?

可能的解决方案:

1) 创建启动管理器脚本来执行模型并检查其他进程是否在 while 循环中完成?或者在模型结束时调用函数?

2) 在每个周期结束时做一些事情,写简单的文本文件或类似的东西。这会被另一个进程接收。

3) 使用 psutil 检查 exe 是否正在运行 https://github.com/giampaolo/psutil

    import psutil

    def is_alive():

        for pid in psutil.pids():
            p = psutil.Process(pid)
            if p.name() == "wrf.exe":
                print("Process is alive")
                return True

        return False

【讨论】:

    猜你喜欢
    • 2011-11-18
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    • 2019-05-08
    • 2021-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多