-4

I have below code in tes.py file.

#!/usr/bin/python
import os

path = '/tmp'
f_path = os.chdir( path )
f = os.getcwd()
print f
os.system('cd f')

I want to get into /tmp directory when I execute tes.py file. But I am getting following error.

[rishb@xxxxxxx ~]$ ./tes.py
/tmp
sh: line 0: cd: f: No such file or directory

Is there any way to achieve my goal in python?

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
Rishab
  • 87
  • 1
  • 1
  • 6

1 Answers1

4

use os.chdir

cd is a bash internal command, which change cwd of the CURRENT process, os.system create a subprocess, and the subprocess can not change cwd of the python process

And python can't change cwd of bash who is its parent.

You can't change cwd of bash using any program, except bash's source command

Zang MingJie
  • 5,164
  • 1
  • 14
  • 27