
Why a program doesn't work when run from a batch file, but works when clicked
A customer asked for help writing a batch file to launch a program. For some reason, the program displayed an error message when the batch file ran it, whereas it worked fine when they double-clicked the program from Ex…
以下正文同步自 Hacker News 最新,版权归原站所有,已转换为易读排版。
A customer asked for help writing a batch file to launch a program. For some reason, the program displayed an error message when the batch file ran it, whereas it worked fine when they double-clicked the program from Explorer.
I immediately suspected that they were not setting the current directory.
Some time ago, I noted that when you double-click a file in Explorer, Explorer sets the current directory of the program to the directory containing the thing that you double-clicked. This is done to accomodate programs that look for ancillary files in the current directory. The example I had was a hypothetical LitWare Writer program that, when given an ABC.LIT file, looks for related files like ABC.LTC (the table of contents) and ABC.LDC (the custom dictionary) in the current directory.
This also happens if you double-click the .exe file: The current directory is set to the directory that contains the executable.
My guess is that the customer’s program looks for ancillary files relative to its current directory, but the batch file ran the program by its full path without changing the current directory to match the program’s path.
The customer confirmed that explicitly changing the directory fixed the program. (More specifically, they used pushd to change the directory and then popd to restore the original directory.)
Bonus chatter: It didn’t come to it, but my second idea would have been to check whether the program had set a custom entry under App Paths to ask for additional directories to be added to the PATH environment variable when the program is run.
正文由 探How 从来源站点 RSS 同步,内容未经改写;遇到排版缺失或需要图片、视频时请以原文为准。