12

I want to pass a chunk of Python code to Python in R with something like system('python ...'), and I'm wondering if there is an easy way to emulate the python console in this case. For example, suppose the code is "print 'hello world'", how can I get the output like this in R?

>>> print 'hello world'
hello world

This only shows the output:

> system("python -c 'print \"hello world\"'")
hello world

Thanks!

BTW, I asked in r-help but have not got a response yet (if I do, I'll post the answer here).

2
  • Have you considered using RPy? Commented Apr 15, 2012 at 5:07
  • 2
    the problem is I want to run python code in R, instead of R code in python, so RPy is probably not an option here; or did I miss something obvious?... Commented Apr 15, 2012 at 18:24

3 Answers 3

12

Do you mean something like this?

export NUM=10
R -q -e "rnorm($NUM)"

You might also like to check out littler - http://dirk.eddelbuettel.com/code/littler.html

UPDATED

Following your comment below, I think I am beginning to understand your question better. You are asking about running python inside the R shell.

So here's an example:-

# code in a file named myfirstpythonfile.py

a = 1 
b = 19
c = 3 
mylist = [a, b, c]
for item in mylist:
    print item

In your R shell, therefore, do this:

> system('python myfirstpythonfile.py')
1
19
3

Essentially, you can simply call python /path/to/your/python/file.py to execute a block of python code.

In my case, I can simply call python myfirstpythonfile.py assuming that I launched my R shell in the same directory (path) my python file resides.

FURTHER UPDATED

And if you really want to print out the source code, here's a brute force method that might be possible. In your R shell:-

> system('python -c "import sys; sys.stdout.write(file(\'myfirstpythonfile.py\', \'r\').read());"; python myfirstpythonfile.py')
a = 1
b = 19
c = 3
mylist = [a, b, c]
for item in mylist:
    print item
1
19
3

AND FURTHER FURTHER UPDATED :-)

So if the purpose is to print the python code before the execution of a code, we can use the python trace module (reference: http://docs.python.org/library/trace.html). In command line, we use the -m option to call a python module and we specify the options for that python module following it.

So for my example above, it would be:-

$ python -m trace --trace myfirstpythonfile.py
 --- modulename: myfirstpythonfile, funcname: <module>
myfirstpythonfile.py(1): a = 1
myfirstpythonfile.py(2): b = 19
myfirstpythonfile.py(3): c = 3
myfirstpythonfile.py(4): mylist = [a, b, c]
myfirstpythonfile.py(5): for item in mylist:
myfirstpythonfile.py(6):     print item
1
myfirstpythonfile.py(5): for item in mylist:
myfirstpythonfile.py(6):     print item
19
myfirstpythonfile.py(5): for item in mylist:
myfirstpythonfile.py(6):     print item
3
myfirstpythonfile.py(5): for item in mylist:
 --- modulename: trace, funcname: _unsettrace
trace.py(80):         sys.settrace(None)

Which as we can see, traces the exact line of python code, executes the result immediately after and outputs it into stdout.

Sign up to request clarification or add additional context in comments.

8 Comments

No, I'm primarily asking a way to run python scripts like the way we call source(file, echo=TRUE) in R. It looks like the code module in python may help (read-eval-print loops), but I'm wondering if python has such a function that can be called directly. I'm new to python. Thanks!
You simply run python scripts (block of python code in a python file) in the command line by calling "python thefilename". So your system() call in R shell should do the same. I have updated my answer above.
Yes, but the question was also, how to print the python-code before execution. Is there some flag for python, like -x for bash scripts?
I don't think there's an equivalent of -x in bash for python.
But if the scenario is to do debugging (from what I understand, -x in bash is primarily used for debugging purposes), then python -d is somewhat similar but it still does not print out the source code.
|
2

The system command has an option called intern = FALSE. Make this TRUE and Whatever output was just visible before, will be stored in a variable.

Now run your system command with this option and you should get your output directly in your variable. Like this

tmp <- system("python -c 'print \"hello world\"'",intern=T)

1 Comment

Sorry, but that is not what I want. I want to emulate the python console (the REPL interface); not only executing the code as a whole, and gather results after that. I'm aware of system(..., intern=TRUE).
0

My work around for this problem is defining my own functions that paste in parameters, write out a temporary .py file, and them execute the python file via a system call. Here is an example that calls ArcGIS's Euclidean Distance function:

py.EucDistance = function(poly_path,poly_name,snap_raster,out_raster_path_name,maximum_distance,mask){

    py_path = 'G:/Faculty/Mann/EucDistance_temp.py'
    poly_path_name = paste(poly_path,poly_name, sep='')

    fileConn<-file(paste(py_path))
    writeLines(c(
        paste('import arcpy'),
        paste('from arcpy import env'),
        paste('from arcpy.sa import *'),
        paste('arcpy.CheckOutExtension("spatial")'),

        paste('out_raster_path_name = "',out_raster_path_name,'"',sep=""),
        paste('snap_raster = "',snap_raster,'"',sep=""),
        paste('cellsize =arcpy.GetRasterProperties_management(snap_raster,"CELLSIZEX")'),
        paste('mask = "',mask,'"',sep=""),
        paste('maximum_distance = "',maximum_distance,'"',sep=""),
        paste('sr = arcpy.Describe(snap_raster).spatialReference'),

        paste('arcpy.env.overwriteOutput = True'),
        paste('arcpy.env.snapRaster = "',snap_raster,'"',sep=""),
        paste('arcpy.env.mask = mask'),
        paste('arcpy.env.scratchWorkspace ="G:/Faculty/Mann/Historic_BCM/Aggregated1080/Scratch.gdb"'),
        paste('arcpy.env.outputCoordinateSystem = sr'),


        # get spatial reference for raster and force output to that
        paste('sr = arcpy.Describe(snap_raster).spatialReference'),
        paste('py_projection = sr.exportToString()'),     
        paste('arcpy.env.extent = snap_raster'),
        paste('poly_name = "',poly_name,'"',sep=""),
        paste('poly_path_name = "',poly_path_name,'"',sep=""),

        paste('holder = EucDistance(poly_path_name, maximum_distance, cellsize, "")'),
        paste('holder = SetNull(holder < -9999, holder)'),
        paste('holder.save(out_raster_path_name) ')

    ), fileConn, sep = "\n")
    close(fileConn)

    system(paste('C:\\Python27\\ArcGIS10.1\\python.exe', py_path))
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.