*! version 0.1.0 22aug2013
help python

Title

python -- use the Python language within Stata

Syntax

python
[varlist]
[if] [in]
[,
options]

file(filename) run Python file

args(string) arguments for the Python file or interactive
session

Options

file(filename) specifies a Python file to execute. Without this option,
the command will start an interactive Python session.

args(string) specifies arguments for the file or
interactive session. The number of arguments is stored in a local macro
_pynargs, and the arguments are stored in local macros _pyarg0,
_pyarg1, etc.

Description

python is a convenience wrapper for the python_plugin plugin, which
makes the Python language available within Stata. The user can execute
Python files or use Python in an interactive interpreter.

The plugin provides functions for interacting with Stata data,
matrices, macros, and numeric scalars. These functions all have the prefix
st_, in analogy with Mata's st_ functions. There are about half as
many such functions as there are in Mata.

See python_plugin.pdf for more information.

Examples

. python

python (type exit() to exit)

. for i in range(5): print(i)
0
1
2
3
4

. bool("only single-line inputs allowed")
True

. st_local("_pynargs")
'0'

. st_local("_pynvars")
'0'

. exit()

. clear

. sysuse auto
(1978 Automobile Data)

. python make price trunk if mod(_n,2), args(arg1 "a r g 2" arg3)

python (type exit() to exit)

. n_args = int(st_local("_pynargs"))

. n_opt_vars = int(st_local("_pynvars"))

. n_args, n_opt_vars
(3, 3)

. for i in range(n_args): print(st_local("_pyarg" + str(i)))
arg1
a r g 2
arg3

. for i in range(n_opt_vars): print(st_local("_pyvar" + str(i)))
make
price
trunk

. st_ifobs(0)
True

. "keep in mind Stata indexing is 1-based, Python indexing is 0-based"
'keep in mind Stata indexing is 1-based, Python indexing is 0-based'

. st_ifobs(1)
False

. funcs = sorted([x for x in globals() if x.startswith("st_")])

. template = "{:>15}{:>15}{:>15}{:>15}"

. for i in range(0, len(funcs)-4, 4): print(template.format(*funcs[i:i+4]))
st_Matrix st_View st_cols st_data
st_format st_global st_ifobs st_in1
st_in2 st_isfmt st_islmname st_ismissing
st_isname st_isnumfmt st_isnumvar st_isstrfmt
st_isstrvar st_isvarname st_local st_matrix_el
st_nobs st_numscalar st_nvar st_rows
st_sdata st_sstore st_store st_varindex

. "see python_plugin.pdf for more info"
'see python_plugin.pdf for more info'

. exit()

Authors

James Fiedler, Universities Space Research Association

Email: jrfiedler@gmail.com