Running Python script using WshShell.Run in VBS does not generate output file

回眸只為那壹抹淺笑 提交于 2020-01-25 05:38:40

问题


I've got a problem with some VB scripting - it doesn't seem like it should be terribly difficult to solve, but even after trudging through many a page of Google I have yet to find a solution.

[The problem]

Here is my python file (test.py), simplified to just show the problem:

f = open("testing.txt", 'w')
f.write("oh hai\n")
f.close()

Of course, when run directly from the command line, this generates the file as you'd expect.

However, when run in a simple .vbs script (WARNING: My vbs skills are lacking. This is probably why I am having a problem. So far I haven't had many issues, apart from hating life from using XP to code when I'm used to using vim)

Set WshShell = WScript.CreateObject("WScript.Shell")
cmd = "C:\Python27\python test.py"
WshShell.Run cmd

no output file is generated! At all! It's infuriating, as when I input that exact command ("C:\Python27\python test.py") into the run program from the start menu, it works!

[System info]

At work, so they're on Windows XP. Everything else is pretty standard, or so I'm lead to believe.

EDIT: Changed "C:\Python27\testing.py" to just "testing.py". This was left over from when I was trying to solve it, and thought maybe it was putting the files somewhere outside of the destination folder.


回答1:


First, your Python script looks suspicious, I doubt the backslashes work in a simple string. At least, in my test, it didn't work, I just replaced them with forward slashes.

Next, you can see the error message by prepending cmd with cmd /k, the run window remains on screen. You can see the .py file isn't found, because it isn't in the current directory. You have to specify an absolute path to this file, perhaps by getting the current path from the script.

[EDIT] I finally got a working code (my VBS is a bit rusty...)

Dim wshShell, fso, loc, cmd

Set fso = CreateObject("Scripting.FileSystemObject")
loc = fso.GetAbsolutePathName(".")
WScript.Echo loc

'~ cmd = "%ComSpec% /k C:\Languages\Python\python.exe " + loc + "\test.py"
cmd = "C:\Languages\Python\python.exe " + loc + "\test.py"
WScript.Echo cmd

Set wshShell = CreateObject("WScript.Shell")
wshShell.Run cmd

You can also check the arguments if a path is provided:

if WScript.Arguments.Count = 0 then
    loc = fso.GetAbsolutePathName(".")
else
    loc = WScript.Arguments(0)
end if

Such script is better run with cscript instead of default wscript.




回答2:


Try

f = open("C:\\Python27\\testing.txt", 'w')

instead of your first line.



来源:https://stackoverflow.com/questions/6732543/running-python-script-using-wshshell-run-in-vbs-does-not-generate-output-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!