Is it possible to change the directory and change it if the script ends?

Trying to answer a question for another user , I came across something that aroused my curiosity:

import os
os.chdir('..')

The working directory will be changed to Python, so if I'm in /home/username/and I run os.chdir('..'), any subsequent code will work as if I were in /home/. For example, if I then do:

import glob
files = glob.glob('*.py')

fileswill be a list of .pyfiles in /home/, not in /home/username/. However, as soon as the script exits, I will return to /home/username/, or in whatever directory I started the script initially.

I found that the same thing happens with shell scripts. If I have the following script:

#!/bin/bash

cd /tmp
touch foo.txt

script /home/username/ foo.txt /tmp/, script, /home/username/ not /tmp/.

, - , "" , , , script ~$ python myscript.py, , script , script .

+4
1

, Python bash (, script).

source, (shell) script . .. script source foomaker.bash bash foomaker.bash

+1

Source: https://habr.com/ru/post/1656266/


All Articles