如何将VBScript中InputBox获取的变量返回至Python?
Got it, let's fix this so you can get that InputBox value back into Python. The problem with using os.system() is that it only returns the command's exit code—not any text output from the VBScript. Here's a straightforward solution:
Step 1: Update Your VBScript to Output the Value
First, modify your SAVE.vbs to print the savename variable to the console. VBS uses WScript.Echo to send output to standard out, which Python can then capture:
Dim savename savename = InputBox("Name to save file as: ", "Save File") WScript.Echo savename ' This sends the value to stdout
Step 2: Use Python's subprocess Module to Capture Output
Replace os.system() with subprocess.run()—this module lets you capture the output from external scripts. We'll use cscript.exe (the console-based VBS engine) instead of the default wscript.exe (which runs in GUI mode) to ensure output goes to the console.
Here's the updated Python code:
import subprocess # Run the VBS script with cscript to capture console output result = subprocess.run( ["cscript.exe", "//nologo", "SAVE.vbs"], capture_output=True, text=True ) # Clean up the output (remove extra newline characters) savename = result.stdout.strip() # Now you can use the savename variable in Python! if savename: print(f"Received save name: {savename}") else: print("User canceled the input dialog.")
Quick Explanations:
cscript.exe //nologo: Runs the VBS in console mode, and//nologohides the initial copyright message so it doesn't mess up your output.capture_output=True: Tells subprocess to capture both stdout and stderr.text=True: Returns output as a string instead of raw bytes, making it easier to work with..strip(): Removes trailing newlines or whitespace from the VBS output.
If you need to handle errors (like if the VBScript fails), you can check result.returncode—a value of 0 means the script ran successfully, while non-zero values indicate an error.
内容的提问来源于stack exchange,提问作者awillers55

