Is it possible to combine python output with html? I want to include the integer i in the note string (like the blue number)
Simplest way to do it is construct the string:
htmlOutput = '<h2>Note: '+ str(i) +'</h2>'
and inject the string in your snippet:
from IPython.core.display import display, HTML
for i in range(10):
htmlOutput = '<h2>Note: '+ str(i) +'</h2>'
display(HTML(htmlOutput))
This should work for you :
from IPython.core.display import display,HTML
for i in range(10):
display(HTML('<h2>Note %s</h2> '%i))
The output willl be:
Note 0
Note 1
Note 2
Note 3
Note 4
Note 5
Note 6
Note 7
Note 8
Note 9
I am running a simple R script in python using the following code.
import rpy2.robjects as robjects
r=robjects.r
output = r.source("sample.R")
Now when I print the output
print (output)
I am getting script's last variable only as an output and not all the variable (which I was not expecting. Also I was thinking if I call c or data, the results will be printed as such but python isn't identifying these variables coded in R). I am not sure how to call all these variables.
I am writing very simple code in R script just for testing. My R script looks like:
a <- 1
b <- 3
c <- a + b
data = 1:20
now on calling the script and printing the results I am getting these the following at output. I am not sure what's happening.
$value
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
$visible
[1] FALSE
I am not sure how to exactly print variable as it is from R to python. Please guide me to it. Your help will be appreciated.
Regards
Your variable output will only store the output from the source file, which is exactly what you get, id est the last variable. But all the variables actually live somewhere, in an R environment, which you can get with robjects.globalenv.
Knowing that you can easily retrieve the value for each variable that you created in R:
import rpy2.robjects as robjects
robjects.r.source("sample.R")
print(robjects.globalenv["a"])
print(robjects.globalenv["b"])
print(robjects.globalenv["c"])
print(robjects.globalenv["data"])
I am currently working on a code to find a value C which I will then compare against other parameters. However, whenever I try to run my code I receive this error: ValueError: math domain error. I am unsure why I am receiving this error, though I think it's how I setup my equation. Maybe there is a better way to write it. This is my code:
import os
import math
path = "C:\Users\Documents\Research_Papers"
uH2 =5
uHe = 3
eH2 = 2
eHe = 6
R = ((uH2*eH2)/(uHe*eHe))
kH2=[]
kHe=[]
print(os.getcwd()) # see where you are
os.chdir(path) # use a raw string so the backslashes are ok
print(os.getcwd()) # convince yourself that you're in the right place
print(os.listdir(path)) # make sure the file is in here
myfile=open("hcl#hfs.dat.txt","r")
lines=myfile.readlines()
for x in lines:
kH2.append(x.split(' ')[1])
kHe.append(x.split(' ')[0])
myfile.close()
print kH2
print kHe
g = len(kH2)
f = len(kHe)
print g
print f
for n in range(0,7):
C = (((math.log(float(kH2[n]),10)))-(math.log(float(kHe[n]),10)))/math.log(R,10)
print C
It then returns this line saying that there is a domain error.
C = (((math.log(float(kH2[n]),10)))-(math.log(float(kHe[n]),10)))/math.log(R,10)
ValueError: math domain error
Also, for the text file, I am just using a random list of 6 numbers for now as I am trying to get my code working before I put the real list of numbers in. The numbers I am using are:
5 10 4 2
6 20 1 2
7 30 4 2
8 40 3 2
9 23 1 2
4 13 6 2
Try to check if the value inside the log is positive as non-positive value to a log function is a domain error.
Hope this helps.
I have three list:
alist=[1,2,3,4,5]
blist=['a','b','c','d','e']
clist=['#','#','$','&','*']
I want my output in this format:
1 2 3 4 5
a b c d e
# # $ & *
I am able to print in correct format but when i am having list with many elements it's actually printing like this:
1 2 3 4 5 6 ..........................................................................
................................................................................
a b c d e ............................................................................
......................................................................................
# # $ & * .............................................................................
.......................................................................................
but I want my output like this:
12345....................................................................
abcde...................................................................
##$&*...................................................................
............................................................... {this line is from alist}
................................................................ {this line is from blist}
................................................................ {this line is from clist}
Try the following:
term_width = 80
all_lists = (alist, blist, clist)
length = max(map(len, all_lists))
for offset in xrange(0, length, term_width):
print '\n'.join(''.join(map(str, l[offset:offset+term_width])) for l in all_lists)
This assumes terminal width is 80 characters, which is the default. You might want to detect it's actual width with curses library or something based on it.
Either way, to adapt to any output width you only need to change term_width value and the code will use it.
It also assumes all elements are 1-character long. If it's not the case, please clarify.
If you need to detect terminal width, you may find some solutions here: How to get Linux console window width in Python
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).
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.
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)
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))
}