Search code examples
pythonwindowsoperating-systemexecutableworking-directory

Python change the working directory for an exe opened with startfile


In python i'm using the os.startfile command to start a windows executable that does especific stuff in its own folder, the python code is running from another folder, so when I start the file, it starts in the python script's working directory, but it has to start in its own directory. I've tried to use os.chdir(path) to change the working directory, but it fails, the file still not runs in it's own folder. I thought maybe there is a command like shortcut's "Start in" line. I've searched everywere, but not success. The only solution comes to my mind is to create a shortcut and add the "start in" line, then launch the shortcut, but that is very impractical.


Solution

  • Don't use os.startfile, for starters. Use subprocess, you can then use cwd argument of Popen.

    import subprocess
    process = subprocess.Popen('command', cwd = 'directory')
    

    If you really want to use ShellExecute, then the best way will be to skip os.startfile and call it directly with ctypes (or look whether it's in pywin32 somewhere).