0

How to change to /var/opt directory in terminal using python.

tried this

sudo bash and entered pass

root@user :

ran python code -

code :

 import os 
 os.chdir(r"/var/opt/backups")

 os.chdir("/var/opt/backups")

but the directory wont change

have tried os.chdir(path) mentioned os.chdir(r"/var/opt/backups") pl check.

  • You want your python code to change the current directory in the bash from which you ahve launched the script? – FlyingTeller Jul 04 '19 at 07:22
  • 1
    Possible duplicate of [How do I change directory (cd) in Python?](https://stackoverflow.com/questions/431684/how-do-i-change-directory-cd-in-python) – Zhubei Federer Jul 04 '19 at 07:23
  • @Zhubei-Federer Op is obviously aware of the `chdir` command which is the accepted answer in your linked question – FlyingTeller Jul 04 '19 at 07:25
  • i went to sudo bash and when i run the python code there it should change dir. tried os.chdir(path). but it isnt working for /var/otp –  Jul 04 '19 at 07:28
  • @Zhubei-Federer im aware of os.chdir mentioned in your linked q. pl check and mark as dup. Dont do it randomly by just looking at the question –  Jul 04 '19 at 07:29

1 Answers1

0

os.chdir is not for changing the directory in the shell from which you might have launched your script, but rather change the working directory of your python script.

What you are trying cannot be done for a simple reason: How should your python script be aware of the fact that you called it from a bash? What should happen if you try to run it from somewhere else?

What you want is to create a bash script:

#!/bin/bash
cd /var/opt

and then source that from your bash by running one of the below:

. <scriptname>
source <scriptname>
FlyingTeller
  • 17,638
  • 3
  • 38
  • 53