假设我想从R运行VBS脚本,并且想将R的值传递给该脚本。如何从R运行VBS脚本,同时将参数从R传递给VBS
例如,在一个简单的文件名为“Msg_Script.vbs”,我的代码:
Dim Msg_Text
Msg_Text = "[Insert Text Here]"
MsgBox("Hello " & Msg_Text)
如何运行,使用R这个脚本,而编辑在R上的参数和/或变量?例如,在上面的脚本中,我将如何编辑Msg_Text
变量的值?
假设我想从R运行VBS脚本,并且想将R的值传递给该脚本。如何从R运行VBS脚本,同时将参数从R传递给VBS
例如,在一个简单的文件名为“Msg_Script.vbs”,我的代码:
Dim Msg_Text
Msg_Text = "[Insert Text Here]"
MsgBox("Hello " & Msg_Text)
如何运行,使用R这个脚本,而编辑在R上的参数和/或变量?例如,在上面的脚本中,我将如何编辑Msg_Text
变量的值?
另一种方式是通过值作为argument to the VBScript
你会写VBS如下:
Dim Msg_Text
Msg_Text = WScript.Arguments(0)
MsgBox("Hello " & Msg_Text)
然后你就会R中创建一个系统命令是这样的:
system_command <- paste("WScript",
'"Msg_Script.vbs"',
'"World"',
sep = " ")
system(command = system_command,
wait = TRUE)
这种方法通过位置参数匹配。 如果你想,你可以使用命名参数。这样一来,你的VBS应该是这样的:
Dim Msg_Text
Msg_Text = WScript.Arguments.Named.Item("Msg_Text")
MsgBox("Hello " & Msg_Text)
然后你创建中的R系统命令是这样的:
system_command <- paste("WScript",
'"Msg_Script.vbs"',
'/Msg_Text:"World"',
sep = " ")
system(command = system_command,
wait = TRUE)
这里的一个稍微-hackish的溶液:
阅读从VBS脚本的线成R(使用readLines()
):
vbs_lines <- readLines(con = "Msg_Script.vbs")
编辑通过查找和替换特定文本中的R行:
updated_vbs_lines <- gsub(x = vbs_lines,
pattern = "[Insert Text Here]",
replacement = "World",
fixed = TRUE)
使用更新后的行创建一个新的VBS脚本:
writeLines(text = updated_vbs_lines,
con = "Temporary VBS Script.vbs")
使用系统命令运行脚本:
full_temp_script_path <- normalizePath("Temporary VBS Script.vbs")
system_command <- paste0("WScript ", '"', full_temp_script_path, '"')
system(command = system_command,
wait = TRUE)
删除新的脚本已运行后:
file.remove("Temporary VBS Script.vbs")