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.
get_local (name)
https://www.stata.com/python/api17/Macro.html#sfi.Macro.getLocal
set_local (name, value)
https://www.stata.com/python/api17/Macro.html#sfi.Macro.setLocal
get_global (name)
https://www.stata.com/python/api17/Macro.html#sfi.Macro.getGlobal
get_scalar (name)
https://www.stata.com/python/api17/Scalar.html?highlight=scalar#sfi.Scalar.getValue
stata_formatted (value, s_format)
https://www.stata.com/python/api17/SFIToolkit.html#sfi.SFIToolkit.formatValue
variable_names ()
variable_names uses ‘getVarCount’ and ‘getVarName’: https://www.stata.com/python/api17/Data.html
drop_var (name)
https://www.stata.com/python/api17/Data.html#sfi.Data.dropVar
obs_count ()
Count the number of observations
https://www.stata.com/python/api17/Data.html#sfi.Data.getObsTotal
pwd ()
https://www.stata.com/python/api17/SFIToolkit.html#sfi.SFIToolkit.getWorkingDir
macro_expand (s)
https://www.stata.com/python/api17/SFIToolkit.html#sfi.SFIToolkit.macroExpand
run_direct (cmds, quietly=False, echo=False, inline=True)
run_direct wraps the most flexible utility Stata provides to run Stata commands: pystata.stata.run
run_single (cmd, echo=False)
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.