簡體   English   中英

從 Python 運行 Stata 並確保沒有錯誤

[英]Run Stata from Python and assure that there was no errors

我知道如何從 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 到 Python 獲得一些反饋,說“已成功完成”?

子進程使用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, "")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM