【问题标题】:Run multiple python scripts from Stata concurrently同时从 Stata 运行多个 python 脚本
【发布时间】:2017-10-05 20:13:06
【问题描述】:

这是我想做的:

  1. 同时从 Stata 调用大约 8 个 python 脚本(以节省时间;如果按顺序执行,它们会花费太长时间)。我知道怎么称呼一个:

    shell "C:/Python34/python.exe" "A:/my code/Test.py"

  2. 让 Stata 等到它们全部完成,然后在 Stata 中执行操作。

是否可以同时调用多个 Python 脚本?

【问题讨论】:

  • 您可以 winexec(而不是 shell)第一个 k-1 和第 kth 个 shell。如果第 k 个比其他一些花费的时间少得多,这将不起作用。否则,看看 -parallel- 。
  • 我认为这会很好,特别是因为我可以选择耗时最长的一个并为缓冲区添加等待命令。谢谢!
  • 另一种选择是编写一个 while 循环来检查 python 脚本的输出,并在它们不全部存在时启动 sleep 命令。
  • 我尝试了 -parallel- 但没有成功。它没有错误地退出,但代码显然没有运行。我想知道“shell”是否不适用于“parallel”?另外,您想将您的解决方案写成答案,以便我接受吗?

标签: parallel-processing stata


【解决方案1】:

我无法访问 Windows 机器,但这样的事情可能会奏效。更改第二部分以匹配您使用 Python 所做的事情。

/* (1) Instead of Python scripts, count some files and store the counts */
winexec rm "/Users/dimitriy/*_count.txt"
winexec find /Users/dimitriy -type f -name '*.ado' | wc -l > ado_count.txt
winexec find /Users/dimitriy -type f -name '*.pdf' | wc -l > pdf_count.txt
winexec find /Users/dimitriy -type f -name '*.do'  | wc -l > do_count.txt


/* (2) Wait for ALL 3 files to be generated since Stata does not wait for winexec commands to finish */
capture ssc install fs, replace

while "`num_files'" != "3" {
    local num_files: word count `r(files)'
    sleep 10000 // sleep 10 seconds
    fs *_count.txt
}

di "All Done!"

回复以下评论:

这没有任何意义,并且由于多种原因无法正常工作。我假设您的 Python 脚本输出了 8 个输出文件。因为我不知道它们是什么,所以我尝试使用 3 个 Mac 命令生成三个文件,以便在第 1 步中为我提供一些工作。第 2 步验证这 3 个文件是否存在,然后再继续。

假设每个 Python 脚本 i 为 i=1,..,8 生成一个名为 output_i.txt 的文件,您将需要这样的内容:

forvalues v=1/8 {
    winexec "C:/Python34/python.exe" "D:/my code/PythonCode`v'.py"
}

capture ssc install fs, replace

while "`num_files'" != "8" {
    local num_files: word count `r(files)'
    sleep 10000 // sleep 10 seconds
    fs output_*.txt
}

【讨论】:

  • fs 这里必须使用ssc install fs 安装,然后代码才能运行。
  • @NickCox 总有一天我会记住这一点的!感谢您再次看到这个。
  • 如果用户编写的命令成为另一个用户的标准曲目的一部分,则它是成功的。这很讨人喜欢。但这对不知道它来自哪里的用户没有帮助!
  • 我认为这是可行的,但是由于没有生成文本文件,因此 do 文件从未继续进行。所以我一定没听懂你在说什么。我所做的是将 (1) 替换为 Python 脚本(例如,winexec "C:/Python34/python.exe" "D:/my code/PythonCode1.py" | wc -l > Code1_count.txt),我认为当它们运行时,将创建文本文件。你能澄清你的解决方案吗?
  • 谢谢,这很有意义!对不起,很密集。我对 Stata 并不陌生,但我之前从未使用过 winexec。
猜你喜欢
  • 2017-06-23
  • 2021-06-06
  • 1970-01-01
  • 2021-07-01
  • 2020-02-19
相关资源
最近更新 更多