1
votes

My a.py file is located in "D:\Cockpit" folder and the python code gets the current directory of the file and saves it in a text file in the same folder. It uses os.getcwd() to get the file path. When I run the python code it gives me as expected results ie D:\Cockpit folder in the text file.

However, I am trying to call this python file via batch file and from an excel macros file through VBA. When I do that, the location that I get is C:\Users\39215\Documents folder in the text file.

How can I change the VBA code or python code so that I get D:\Cockpit as the output?

Python Code:

import os

mainpath = str(os.getcwd())
errors = []
errors.append(mainpath)
fpath = r"D:\Cockpit\Path.txt"
f = open(fpath,"w+")
for i in errors:
    f.write("%s\r\n" % (i))
f.close()

VBA Code:

Sub RunAggregation()
    Dim oShell As Object, oCmd As String, cwd As String
    Dim oExec As Object, oOutput As Object
    Set oShell = CreateObject("WScript.Shell")
    cwd = Application.ActiveWorkbook.Path
    oCmd = cwd & "\batch1.bat"
    MsgBox (oCmd)
    Set oExec = oShell.Exec(oCmd)
    Set oOutput = oExec.StdOut
    Set oOutput = Nothing: Set oExec = Nothing
    Set oShell = Nothing

End Sub

I have tried using ChDir "D:\Cockpit" in VBA, but it doesnt seem to work

1
What are the contents of the batch1.bat file? - YasserKhalil
What about changing the python file. put this line os.chdir('D:\Cockpit') before this line mainpath = str(os.getcwd()) - YasserKhalil

1 Answers

0
votes

Try modifying the python code

import os

os.chdir('D:\Cockpit')
mainpath = str(os.getcwd())
errors = []
errors.append(mainpath)
fpath = "Path.txt"

f = open(fpath, "w+")
for i in errors:
    f.write("%s\r\n" % (i))
f.close()