从Python运行Stata并确保没有错误

2 投票
1 回答
1340 浏览
提问于 2025-05-10 15:38

我知道怎么从Python启动Stata。这里有一个简单的步骤

def dostata(dofile, *params):
    ## Launch a do-file, given the fullpath to the do-file
    ## and a list of parameters.       
    cmd = ["C:\Program Files (x86)\Stata13\StataMP-64.exe", "do", dofile]
    for param in params:
        cmd.append(param)
    a = subprocess.Popen(cmd, shell=True)

path = "C:/My/do/file/dir/"
filename = "try.do"

dostata(path + filename, model, "1", "")

这个方法基本上是有效的。但是它并不能保证Stata程序会顺利完成。我该怎么做才能从Stata得到一些反馈,告诉我“完成成功”呢?

相关文章:

  • 暂无相关问题
暂无标签

1 个回答

3

子进程使用 returncode 来返回一个结果,表示是成功(零)还是失败(非零)。

不过,Stata 的 do 文件并不是普通的可执行文件,而是以 批处理作业 的形式运行。因此,Stata.exe 总是会返回一个成功的代码,因为它会一直运行,不管 .do 文件的输出结果是什么。所以,下面的内容是说,Python 可以读取 Stata 的日志,并把它输出到控制台,让用户看到代码的结果。甚至可以让 Python 检查日志文件中是否有任何 Stata 错误代码,比如 r(1)r(9999),如果在日志文件中找到了这些错误代码,就让 Python 提醒用户。

import os, subprocess

# CURRENT DIRECTORY
cd = os.path.dirname(os.path.abspath(__file__))

def openlog(filename):
    with open(filename, 'r') as txt:
        for line in txt:
            print(line.strip())

def dostata(dofile, logfile, *params):
    ## Launch a do-file, given the fullpath to the do-file
    ## and a list of parameters.       
   cmd = ["C:\Program Files (x86)\Stata13\StataMP-64.exe", "/b", "do", dofile]
   for param in params:
       cmd.append(param)
   a = subprocess.Popen(cmd, shell=True)

   print('STATA OUTPUT:\n')
   openlog(os.path.join(cd, logfile))


path = "C:/My/do/file/dir/"
filename = "try.do"
logname = "try.log"

result = dostata(os.path.join(path, filename), logname, "")

撰写回答