R语言命令行执行代码的3种方式(传递参数和环境变量)

R语言命令行执行代码的3种方式(传递参数和环境变量)

大部分情况在IDE环境中运行R程序,但有时也需要在shell中运行,和其他语言的脚本一样。在shell中如何运行R语言的代码呢?

为了简化使用,把R/Rscript的可执行路径加入path环境变量。(bash,windows cmd)

使用R

首先看看R的help

c:\R> R --arch x64 --help
Usage: Rterm [options] [< infile] [> outfile] [EnvVars]

Start R, a system for statistical computation and graphics, with the
specified options

EnvVars: Environmental variables can be set by NAME=value strings

Options:
  -h, --help            Print usage message and exit
  --version             Print version info and exit
  --encoding=enc        Specify encoding to be used for stdin
  --encoding enc        ditto
  --save                Do save workspace at the end of the session
  --no-save             Don't save it
  --no-environ          Don't read the site and user environment files
  --no-site-file        Don't read the site-wide Rprofile
  --no-init-file        Don't read the .Rprofile or ~/.Rprofile files
  --restore             Do restore previously saved objects at startup
  --no-restore-data     Don't restore previously saved objects
  --no-restore-history  Don't restore the R history file
  --no-restore          Don't restore anything
  --workspace=file      Workspace to be restored
  --vanilla             Combine --no-save, --no-restore, --no-site-file,
                          --no-init-file and --no-environ
  --max-mem-size=N      Set limit for memory to be used by R
  --max-ppsize=N        Set max size of protect stack to N
  -q, --quiet           Don't print startup message
  --silent              Same as --quiet
  --no-echo             Make R run as quietly as possible
  --verbose             Print more information about progress
  --args                Skip the rest of the command line
  --ess                 Don't use getline for command-line editing
                          and assert interactive use
  -f file               Take input from 'file'
  --file=file           ditto
  -e expression         Use 'expression' as input

One or more -e options can be used, but not together with -f or --file

An argument ending in .RData (in any case) is taken as the path
to the workspace to be restored (and implies --restore)

由此可见,R可以接受输入重定向的文件内容,可以通过-f file--file=file指定文件输入。

有一个选项--args可以提示R跳过之后的参数,其实后面的参数作为传递给R进程。脚本中的
commandArgs()函数可以捕获命令行输入的所有参数。其中,trailingOnly = TRUE只获得–args之后的参数。

命令行还可以定义NAME=value形式的环境变量。环境变量的设置和--agrs无关。

举个栗子: (简单起见,增加--vanilla --no-echo参数)
demo.R内容

cat("\n")
cat("commandArgs(trailingOnly = FALSE)\n")
(args1<-commandArgs(trailingOnly = FALSE))

cat("\n") 
cat("commandArgs(trailingOnly = TRUE)\n")
(args2<-commandArgs(trailingOnly = TRUE))

cat("\n")
cat("get environment variable\n")
Sys.getenv("AAA")
Sys.getenv("BBB")

命令:

R --vanilla --no-echo -f demo.R BBB=hehe  --args AAA=haha

结果:

commandArgs(trailingOnly = FALSE)
[1] "C:\\PROGRA~1\\R\\R-40~1.3/bin/x64/Rterm.exe"
[2] "--vanilla"
[3] "--no-echo"
[4] "-f"
[5] "demo.R"
[6] "BBB=hehe"
[7] "--args"
[8] "AAA=haha"

commandArgs(trailingOnly = TRUE)
[1] "AAA=haha"

get environment variable
[1] "haha"
[1] "hehe"

使用Rscript

先看看Rscript的帮助:

Usage: /path/to/Rscript [--options] [-e expr [-e expr2 ...] | file] [args]

--options accepted are
  --help              Print usage and exit
  --version           Print version and exit
  --verbose           Print information on progress
  --default-packages=list
                      Where 'list' is a comma-separated set
                        of package names, or 'NULL'
or options to R, in addition to --no-echo --no-restore, such as
  --save              Do save workspace at the end of the session
  --no-environ        Don't read the site and user environment files
  --no-site-file      Don't read the site-wide Rprofile
  --no-init-file      Don't read the user R profile
  --restore           Do restore previously saved objects at startup
  --vanilla           Combine --no-save, --no-restore, --no-site-file
                        --no-init-file and --no-environ

'file' may contain spaces but not shell metacharacters
Expressions (one or more '-e <expr>') may be used *instead* of 'file'
See also  ?Rscript  from within R

RScript其实R的简化版本,预定义了--no-echo --no-restore -f 和 --args参数。

c:\R>Rscript demo.R BBB=hehe  --args AAA=haha

commandArgs(trailingOnly = FALSE)
[1] "C:\\PROGRA~1\\R\\R-40~1.3\\bin\\x64\\Rterm.exe"
[2] "--no-echo"
[3] "--no-restore"
[4] "--file=demo.R"
[5] "--args"
[6] "BBB=hehe"
[7] "--args"
[8] "AAA=haha"

commandArgs(trailingOnly = TRUE)
[1] "BBB=hehe" "--args"   "AAA=haha"

get environment variable
[1] "haha"
[1] "hehe"

使用R CMD BATCH

c:\R>R CMD BATCH --help
Usage: R CMD BATCH [options] infile [outfile]

Run R non-interactively with input from infile and place output (stdout
and stderr) to another file.  If not given, the name of the output file
is the one of the input file, with a possible '.R' extension stripped,
and '.Rout' appended.

Options:
  -h, --help            print short help message and exit
  -v, --version         print version info and exit
  --no-timing           do not report the timings
  --                    end processing of options

Further arguments starting with a '-' are considered as options as long
as '--' was not encountered, and are passed on to the R process, which
by default is started with '--restore --save'.

Report bugs at <https://bugs.R-project.org>.

R CMD BATCH似乎只能接受输入文件和输出文件,而且默认是--restore --save的参数。

c:\R>R CMD BATCH --no-echo --encoding="UTF-8" demo.R  demo.out --args AAA=haha

没有输出,打开文件demo.out,文件内容是:


commandArgs(trailingOnly = FALSE)
[1] "C:\\PROGRA~1\\R\\R-40~1.3/bin/x64/Rterm.exe"
[2] "-f"                                         
[3] "demo.R"                                     
[4] "--restore"                                  
[5] "--save"                                     
[6] "--no-echo"                                  
[7] "--encoding=UTF-8"                           

commandArgs(trailingOnly = TRUE)
character(0)

get environment variable
[1] ""
[1] ""
> proc.time()
用户 系统 流逝 
0.15 0.04 0.18 

由此可见,R CMD BATCH file不能给file传递参数,也不能传递环境变量。

<think>好的,用户想了解如何在TCLShell脚本之间传递变量。首先,我需要回忆一下这两种脚本语言的特点以及它们之间的交互方式。根据提供的引用资料,用户已经提到了在TCL中调用CSH脚本的方法,以及Shell脚本中的变量处理,还有如何在Shell脚本中引用其他脚本传递参数。这可能对解决问题有帮助。 首先,TCLShell脚本都是解释型语言,常用于自动化任务系统管理。它们之间的变量传递可能涉及到环境变量命令行参数、文件交互等方式。根据引用[1],TCL可以通过exec命令执行外部脚本,比如Shell脚本,并可能获取其输出。而Shell脚本中的变量可以通过环境变量或者标准输出来传递。 接下来,我需要考虑几种可能的传递方式: 1. **环境变量传递**:在Shell脚本中设置环境变量,然后在TCL中读取这些变量。或者在TCL中设置环境变量,再在Shell脚本中获取。这种方法需要注意环境变量的作用域,父进程设置的环境变量是否会被子进程继承。 2. **命令行参数传递**:通过执行脚本时传递参数。例如,TCL脚本调用Shell脚本时,将变量作为参数传入,或者反过来。这需要处理参数的解析,比如在Shell中使用$1、$2获取参数,在TCL中通过$argv获取。 3. **标准输入输出传递**:通过执行脚本后捕获输出。比如,TCL使用exec执行Shell脚本并获取其输出结果,然后解析输出中的变量值。或者Shell脚本读取TCL脚本的输出。 4. **文件传递**:将变量值写入临时文件,然后在另一个脚本中读取该文件。这种方法适用于较大的数据或需要持久化的情况,但需要注意文件权限清理。 根据引用[4],Shell脚本中的变量可以通过awk传递,可能涉及到字符串拼接引号的处理。这提示在跨语言传递变量时,需要注意引号变量展开的问题。 现在需要具体分析每种方法的实现步骤,并参考用户提供的引用资料中的例子。例如,引用[1]中提到TCL使用exec执行CSH脚本,所以TCL可以捕获exec命令的输出。例如,在TCL中执行Shell脚本,并将输出保存到变量中: ```tcl set result [exec bash script.sh] ``` 然后,解析result变量中的内容。类似地,Shell脚本可以通过echo输出变量,供TCL捕获。 环境变量的例子,比如在Shell中导出变量: ```bash export MY_VAR="value" ``` 然后在TCL中通过全局环境变量获取: ```tcl set envVar $env(MY_VAR) ``` 需要注意的是,环境变量在子进程中可能无法修改父进程的环境,所以如果TCL启动Shell脚本,Shell脚本修改的环境变量不会影响TCL,除非在同一个进程中执行,比如使用source命令,但TCL无法直接source Shell脚本,可能需要通过其他方式命令行参数的例子,比如TCL调用Shell脚本并传递参数: ```tcl exec bash script.sh $arg1 $arg2 ``` 在Shell脚本中,通过$1、$2获取这些参数。 反过来,Shell调用TCL脚本时,可以通过类似的方式传递参数: ```bash tclsh script.tcl "$var1" "$var2" ``` 然后在TCL脚本中通过$argv获取。 另外,引用[3]中提到在Shell脚本中使用source来引用其他脚本,这可能涉及到变量的共享,但这对TCLShell之间的传递可能不适用,因为它们是不同的解释器。 还需要注意不同Shell的差异,比如bashcsh的变量语法可能不同,引用[2]提到默认是bash,所以用户可能在用bash的情况下需要调整。 总结,可能的步骤是: 1. 使用环境变量,在Shell中导出变量,TCL通过$env获取。 2. 通过命令行参数传递3. 通过标准输出捕获变量值。 4. 使用临时文件。 需要给出具体的示例,并说明每种方法的适用场景注意事项。例如,环境变量适合传递少量数据,命令行参数适合明确的参数传递,标准输出适合获取脚本的输出结果,文件适合大量数据或复杂结构。 同时,需要注意跨平台安全性问题,比如处理特殊字符,避免注入攻击等。例如,在传递参数时正确转义引号空格。 最后,根据用户的问题,需要将这些方法整理成清晰的步骤,并附上代码示例,确保用户能够理解应用。同时,生成相关问题,帮助用户进一步学习。</think>在TCLShell脚本之间传递变量可以通过以下方法实现,每种方法根据具体场景选择: --- ### 一、通过环境变量传递 **原理**:在父进程中设置环境变量,子进程继承环境变量。 #### 1. Shell → TCL 传递变量 **Shell脚本** (`set_var.sh`): ```bash #!/bin/bash export MY_VAR="Hello from Shell" # 导出环境变量 tclsh script.tcl # 调用TCL脚本 ``` **TCL脚本** (`script.tcl`): ```tcl puts "Received from Shell: $env(MY_VAR)" # 读取环境变量 ``` #### 2. TCL → Shell 传递变量 **TCL脚本** (`set_var.tcl`): ```tcl #!/usr/bin/tclsh set ::env(CUSTOM_VAR) "Hello from TCL" # 设置环境变量 exec bash script.sh # 调用Shell脚本 ``` **Shell脚本** (`script.sh`): ```bash #!/bin/bash echo "Received from TCL: $CUSTOM_VAR" # 读取环境变量 ``` --- ### 二、通过命令行参数传递 **原理**:调用脚本时将变量作为参数传递。 #### 1. Shell → TCL 传递参数 **Shell脚本**: ```bash #!/bin/bash value="123" tclsh script.tcl "$value" # 传递变量值作为参数 ``` **TCL脚本** (`script.tcl`): ```tcl set arg1 [lindex $argv 0] # 获取第一个参数 puts "Received from Shell: $arg1" ``` #### 2. TCL → Shell 传递参数 **TCL脚本**: ```tcl set value "456" exec bash script.sh $value # 传递参数给Shell脚本 ``` **Shell脚本** (`script.sh`): ```bash #!/bin/bash echo "Received from TCL: $1" # 通过$1获取第一个参数 ``` --- ### 三、通过标准输入输出捕获 **原理**:通过执行脚本并捕获输出结果。 #### 1. 在TCL中获取Shell脚本的输出 **Shell脚本** (`get_value.sh`): ```bash #!/bin/bash echo "output_value" # 输出变量值 ``` **TCL脚本**: ```tcl set result [exec bash get_value.sh] # 捕获Shell脚本的输出 puts "Received from Shell: $result" ``` #### 2. 在Shell中获取TCL脚本的输出 **TCL脚本** (`output.tcl`): ```tcl puts "tcl_output_value" # 输出变量值 ``` **Shell脚本**: ```bash value=$(tclsh output.tcl) # 捕获TCL脚本的输出 echo "Received from TCL: $value" ``` --- ### 四、通过临时文件传递 **原理**:将变量写入文件,另一个脚本读取文件内容。 #### 1. Shell写入,TCL读取 **Shell脚本** (`write.sh`): ```bash #!/bin/bash echo "file_content" > /tmp/shared.tmp # 写入临时文件 ``` **TCL脚本** (`read.tcl`): ```tcl set fp [open /tmp/shared.tmp r] set content [read $fp] close $fp puts "Received from Shell: $content" ``` #### 2. TCL写入,Shell读取 **TCL脚本** (`write.tcl`): ```tcl set fp [open /tmp/shared.tmp w] puts $fp "tcl_content" close $fp ``` **Shell脚本** (`read.sh`): ```bash content=$(cat /tmp/shared.tmp) echo "Received from TCL: $content" ``` --- ### 注意事项 1. **作用域限制**:环境变量仅在子进程继承父进程环境时有效,无法反向修改父进程环境。 2. **安全性**:传递敏感数据时避免使用命令行参数(可能被其他进程窥探)。 3. **临时文件清理**:使用后需删除临时文件,避免残留。 4. **特殊字符处理**:若变量含空格或特殊符号,需用引号包裹(如`exec bash script.sh "$value"`)[^2][^4]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值