RanRag
RanRag

Reputation: 49567

Change current working directory in command prompt using python

I am trying to write a python script that will change my cwd to the desired directory. I was not able to do this task directly from python so I wrote a simple batch script to do that.

Changedir.bat

@echo off
chdir /D F:\cygwin\home\

If I execute the above script directly in my cmd it works fine but if I try to execute it with a python script nothing happens. My cwd remains same.

PythonScript.py

import shlex,subprocess

change_dir = r'cmd.exe /c C:\\Users\\test.bat'
command_change = shlex.split(change_dir)
subprocess.call(command_change)

Upvotes: 2

Views: 9698

Answers (3)

mrdiskodave
mrdiskodave

Reputation: 359

You could try this. It works in Linux to change the CWD of the current shell. It is horrible.

def quote_against_shell_expansion(s):
    import pipes
    return pipes.quote(s)

def put_text_back_into_terminal_input_buffer(text):
    # use of this means that it only works in an interactive session
    # (and if the user types while it runs they could insert
    #  characters between the characters in 'text')
    import fcntl, termios
    for c in text:
        fcntl.ioctl(1, termios.TIOCSTI, c)

def change_shell_working_directory(dest):
    put_text_back_into_terminal_input_buffer("cd "+quote_against_shell_expansion(dest)+"\n")

Upvotes: 1

David Heffernan
David Heffernan

Reputation: 612993

If you want to change directory in the command prompt you have to use either cd or a .bat script.

You can't get another process (i.e. Python) to do it because changes to the current directory, made in another process are not reflected back to the parent process. The reason the .bat script works is that it is processed by the command shell that invokes it rather than by a child process.

Upvotes: 2

tchap
tchap

Reputation: 1057

Of course this can't work, because subprocess.call is spawning whole new process for your script. This executes the script in a completely separate environment.

Upvotes: 5

Related Questions