确保从 Excel 运行批处理文件时在 cmd.exe 中使用相对路径
我有一个 Excel 文件,其中有一个在 VB 中调用 Shell 命令的按钮:
Shell(ThisWorkbook.Path & "\python_script.bat", vbNormalFocus)
Shell 命令调用上面运行 Python 脚本的批处理文件:
python python_script.py
所有相关文件(Excel 文件、批处理文件、数据文件、Python 文件) )都位于同一目录中,将此称为 sample_program
,因为我正在为其他人构建此程序,并且我打算让他们简单地解压缩并运行它。
在 Excel 中,测试此功能时,我单击按钮,然后收到此错误:
C:\Users\<user_name>\Documents>python python_script.py
python: can't open file 'python_script.py': [Errno 2] No such file or directory
出于某种原因,尽管所有这些文件都位于同一位置,但 cmd.exe 正在从我的用户目录运行:C:\Users\
我不希望 cmd.exe 使用此路径;我希望它使用 path\to\sample_program
目录。
如何让它使用相对路径,以便当我将此文件夹传输给其他人,并且他们将其放置在任何地方时,它将作为一个独立的单元工作?
I have an Excel file with a button that calls a Shell command in VB:
Shell(ThisWorkbook.Path & "\python_script.bat", vbNormalFocus)
The Shell command calls the above batch file that runs a Python script:
python python_script.py
All the pertinent files (the Excel file, the batch file, the data files, the Python file) are all located in the same directory, call this sample_program
, because I am building this for someone else and I intend for them to simply unzip it and run it.
In Excel, when testing this, I click the button and then get this error:
C:\Users\<user_name>\Documents>python python_script.py
python: can't open file 'python_script.py': [Errno 2] No such file or directory
For some reason, although all these files are in the same location, the cmd.exe is running from my user directory: C:\Users\<user_name>\Documents
I don't want cmd.exe to use this path; I want it to use the path\to\sample_program
directory.
How do I get this to use relative paths so when I transfer this folder to someone else, and they place it anywhere, it will work as a self-contained unit?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
发布评论
评论(2)
您可以使用 Environ("username") 来获取用户登录名,因此对于您的示例(我假设是 Windows 7),
Sub GetDir()
MsgBox "C:\Users\" & Environ("username") & "\Documents"
End Sub
您还可以使用 SpecialFOlders 自动检索某些位置,无论操作系统如何,即
Sub GetPath()
Set wshShell = CreateObject("WScript.Shell")
Documents = wshShell.SpecialFolders("MyDocuments")
MsgBox Documents
End Sub
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
如果
path\to\sample_program
与您的主驱动器位于同一驱动器上,请尝试此操作,或者如果
path\to\sample_program
不存在, 请尝试此操作与您家的驱动器相同的驱动器,或者您事先不知道Try this, if
path\to\sample_program
is on the same drive as your home driveor this if
path\to\sample_program
is not on the same drive as your home drive, or you dont know in advance