2017-08-10 156 views
0

假設我想從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變量的值?

回答

1

另一種方式是通過值作爲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) 
0

這裏的一個稍微-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")