Search code examples
pythonbatch-filesubprocesspopen

Problems running batch files with Python


I am rather new to Python and have been trying to run a .cmd file with it, but it won't run it from the correct location. My file Run_setup.cmd, is setting up another a different software with a bunch of related files and so I have sequestered them to their own folder for my sanity.

Currently I can get the .cmd file to run from the same location as my source code. I know I am messing up the file path for it with cwd=r'%s' based on what the documentation says, but I don't get how.

If cwd is not None, the function changes the working directory to cwd before executing the child. cwd can be a str and path-like object. In particular, the function looks for executable (or for the first item in args) relative to cwd if the executable path is a relative path.

I currently have it using cwd=r' C:\LargeFolder\Files\CorrectFolder' based off this post, and it seems that it works for any file path, but I can't seem to get it to work for me.

from subprocess import Popen

def runCmdfile():
    # File Path to source code:    'C:\LargeFolder\Files'
    myDir = os.getcwd()

    # File Path to .cmd file:      'C:\LargeFolder\Files\CorrectFolder'
    myDir = myDir + '\CorrectFolder'

    runThis = Popen('Run_setup.cmd', cwd=r'%s' % myDir)

    stdout, stderr = runThis.communicate()

What am I missing here, and furthermore what is the purpose of using cwd=r' ' ?


Solution

  • this one works for me:

    def runCmdfile():
        # File Path to source code:    'C:\LargeFolder\Files'
        myDir = os.getcwd()
    
        # File Path to .cmd file:      'C:\LargeFolder\Files\CorrectFolder'
        myDir = os.path.join(myDir, 'CorrectFolder')
    
        # Popen does not take cwd into account for the file to execute
        # so we build the FULL PATH on our own
        runThis = Popen(os.path.join(myDir, 'Run_setup.cmd'), cwd=myDir)
    
        stdout, stderr = runThis.communicate()