Learn R Programming

SnakeCharmR (version 1.0.7.1)

py.exec: Executes arbitrary Python code from R

Description

This function runs Python code that is provided in a character vector.

Usage

py.exec(code, stopOnException = TRUE)

Arguments

code

a character vector containing Python code, typically a single line with indentation and EOL characters as required by Python syntax

stopOnException

if TRUE then stop will be called if a Python exception occurs, otherwise only a warning will be flagged

Details

The character vector containing the code to execute may consist of a single string with EOL and indentation characters embedded.

Alternatively, it can be a character vector, each entry containing one or more lines of Python code.

Examples

Run this code
# NOT RUN {
a <- 1:4
b <- 5:8
py.exec(c("def concat(a,b):", "\treturn a+b"))
py.call("concat", a, b)
# [1] 1 2 3 4 5 6 7 8

# }
# NOT RUN {
py.exec("raise Exception('Stop the presses!')")
# Error in py.exec("raise Exception('Stop the presses!')") (from py.exec.R#48) : 
#   Traceback (most recent call last):
#   File "<string>", line 2, in <module>
# Exception: Stop the presses!
# }
# NOT RUN {
py.exec("raise Exception('Houston, we have a problem!')", stopOnException = FALSE)
# Warning message:
# In py.exec("raise Exception('Houston, we have a problem!')", stopOnException = FALSE) :
#   Traceback (most recent call last):
#   File "<string>", line 2, in <module>
# Exception: Houston, we have a problem!
# }

Run the code above in your browser using DataLab