I'm seeking a way to execute a VBS script without saving it to the disk. My primary language is Python, but I'm open to exploring the use of batch files to achieve this goal. Can anyone offer guidance or a solution for this task?
You can use a COM object to run VBScript (or JScript) code embedded directly in your Python script. Here's an example: (credit). Prerequisite: pywin32 (pip install pywin32
)
import win32com.client
vbhost = win32com.client.Dispatch("ScriptControl")
vbhost.language = "vbscript"
script = """
Dim myReturnValue
Function ExampleMethod()
myReturnValue = 9
Msgbox myReturnValue
End Function
"""
vbhost.AddCode(script)
vbhost.Run("ExampleMethod")
output = vbhost.Eval("myReturnValue")
print (output)
However, there's a catch. ScriptControl
, by default, uses msscript.ocx
which is 32 bit only. Unless you can run your Python script in 32 bit, you'll need an alternative ScriptControl for 64 bit. Fortunately, there's one available for free here. Install that control and the code above will then work in 64 bit.
If you only need to run individual shell commands from Python, you can do it using the WScript.Shell
object which works fine in 64 bit. Here's an example: (credit).
import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
rslt=shell.Popup("Would you like to run Notepad?", 0, "Python WSH Test!",35)
if rslt == 6:
shell.run("notepad")
else:
shell.Popup("Maybe next time.", 4, "Bye!")
In some cases, it's easier to translate the VBScript code to Python and avoid this complication.