Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
443 views
in Technique[技术] by (71.8m points)

r - Rpy2 in python 3.6 working sometimes and sometimes not

I am using rpy2 to run my R script in django project(python is 3.6) and I came across a weird error. sometimes my whole code is working and sometimes r object is NULL.My R version is 4.0.3 on server.

>>>>>>my import statements
import rpy2.robjects as ro
import numpy as np
import rpy2.robjects.packages as rpackages
rpackages.importr('readxl') and some more
>>>>> my code
path2script = os.path.join(settings.BASE_DIR, 'r_scripts', 'script.R')
print('txt_path>>>>>',txt_path)
ro.globalenv['args'] = ro.vectors.StrVector([txt_path])
print('ro.globalenvargs>>>>>>',ro.globalenv['args'])
r = ro.r
print('r>>>>>>>>',r)
obj = r.source(path2script)                 
print('obj>>>>>>>>>',obj)
returnarray  = np.array(obj, dtype="object")
print('returnarray',returnarray)

this is how my terminal looks like when my code is working.

txt_path>>>>> /home/ubuntu/4triangle/r_files/args.txt
ro.globalenvargs>>>>>> [1] "/home/ubuntu/4triangle/r_files/args.txt" 
r>>>>>>>> <rpy2.robjects.R object at 0x7f518ce767b8>
platform: x86_64-pc-linux-gnu
arch: x86_64
os: linux-gnu
system: x86_64, linux-gnu

and this is how my terminal looks like when my code is not working.

txt_path>>>>> /home/ubuntu/4triangle/r_files/args.txt
ro.globalenvargs>>>>>> <rpy2.rinterface_lib.sexp.NULLType object at 0x7f518f663048> [RTYPES.NILSXP]
r>>>>>>>> Error in get_data_from_rscript 'NULLType' object is not callable

exactly at the line "ro.r" python returns me an error which says,

TypeError: 'NULLType' object is not callable"

and again after some time, the same code works without any error.

I'm bit confused about why the r object is getting NULL. Any help would be appreciated.

some code from script.r is as follows :-

server_file_path <- "/home/ubuntu/4triangle/r_files"
setwd(server_file_path)
sp = args[1]
con=file(sp,open="r")
args=c(readLines(con)) 
file_path <- args[1]
file_name <- args[2]

main_function  <- function(){
    if(method == "stochastic"){
        FouResT.stotastic()
    }
  else if(method =="re_reserving"){
    FouResT.reserving()
  }
    else{
        FouResT.ChainLadder()
    }
}   
main_function()
question from:https://stackoverflow.com/questions/65919406/rpy2-in-python-3-6-working-sometimes-and-sometimes-not

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...