sfi.SFIToolkit.stata("quietly gen var1 = 1")
variable_names()['var1']
pystata/sfi functionality
sfi is Stata’s python API, originally intended for interacting with Stata from python within Stata. As such, it can only be imported with Stata running. pystata.stata.run enables running Stata code from python.
For one thing, using wrappers removes the need to constantly import pystata and/or sfi within functions elsewhere to avoid running afoul of CI tests in an environment without Stata installed.
https://www.stata.com/python/api17/Macro.html#sfi.Macro.getLocal
https://www.stata.com/python/api17/Macro.html#sfi.Macro.setLocal
https://www.stata.com/python/api17/Macro.html#sfi.Macro.getGlobal
https://www.stata.com/python/api17/Scalar.html?highlight=scalar#sfi.Scalar.getValue
https://www.stata.com/python/api17/SFIToolkit.html#sfi.SFIToolkit.formatValue
variable_names uses ‘getVarCount’ and ‘getVarName’: https://www.stata.com/python/api17/Data.html
https://www.stata.com/python/api17/Data.html#sfi.Data.dropVar
Count the number of observations
https://www.stata.com/python/api17/Data.html#sfi.Data.getObsTotal
https://www.stata.com/python/api17/SFIToolkit.html#sfi.SFIToolkit.getWorkingDir
https://www.stata.com/python/api17/SFIToolkit.html#sfi.SFIToolkit.macroExpand
run_direct wraps the most flexible utility Stata provides to run Stata commands: pystata.stata.run
run_single uses an sfi function for running a single command that is notably faster than pystata.stata.run but is less versatile and appears less resilient to errors: https://www.stata.com/python/api17/SFIToolkit.html#sfi.SFIToolkit.stata
0
Elapsed time: 0.0001 seconds
0
Elapsed time: 0.0585 seconds
For example, it cannot display graphs, silently quashing them instead:
(Life expectancy, 1998)
Even worse, a subsequent run of sfi.SFIToolkit.stata can be affected by a previous error:
SyntaxError('failed to execute the specified Stata command')
But an intervening blank run seems to set things right:
1
invalid name
So run_single should only be used with care. For when it is used, in case of error-causing input code, it executes sfi.SFIToolkit.stata again (with stdout redirected) to prevent the effects of the error from persisting.