将参数从Mac上的JuPyter笔记本传递到R脚本,反之亦然?

2024-09-24 22:29:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个JuPyter笔记本(Python),希望将参数列表传递到R程序(单独存储在同一目录中)。在R程序执行后,它将把结果传回JuPyter笔记本

我在macOS上

因此,我的问题如下:

  1. 如何将参数从JuPyter(Python)传递到R?我尝试过使用subprocess.Popen,但它似乎不起作用
    command = "/Library/Frameworks/R.framework/Resources/bin/R"
    script = "/Users/me/Desktop/rProgram.R"
    args = [1,2,3] # some arguments to pass to R
    cmd = [command, script] + args
    p = subprocess.Popen(cmd, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
    results = p.communicate()

看来程序没有运行。如果我打印results,我会得到:

ARGUMENT '/Users/me/Desktop/rProgram.R' __ignored__\n\n", b"Fatal error: you must specify '--save', '--no-save' or '--vanilla'\n")

  1. 我的第二个问题是,如何让R程序在JuPyter中将一些变量传回Python?或者等效地,如何让Python从R程序中获取这些变量

Tags: to程序cmd参数scriptargs笔记本jupyter
1条回答
网友
1楼 · 发布于 2024-09-24 22:29:18

发现上面我的目录中有一些错误。在Mac上,Rscript路径被指定为/Library/Frameworks/R.framework/Versions/Current/Resources/Rscript。我在上面的原始代码中使用的路径似乎不会运行R的实例

  1. 在Python方面:
command = "/Library/Frameworks/R.framework/Versions/Current/Resources/Rscript"
script =  "/Users/me/Desktop/rProgram.R"
args = [1,2,3] # some arguments to pass to R
cmd = [command, script] + args

x = subprocess.check_output(cmd, universal_newlines = True, stderr = subprocess.STDOUT)

x是从rProgram.R脚本传回的必需参数

  1. 在R侧:
# Retrieve arguments from Python
args <- commandArgs(trailingOnly = TRUE)

# Perform some functions
some.value <- some.function(args)

# Passing the value back to Python
cat(some.value)

相关问题 更多 >