0

I already tried with

import os
os.system('do stuff')

but i need this to "save the state of what it has done" for example:

os.system('dir')
os.system('cd ..')
os.system('dir')

In this code, the dir will return the same thing, because the cd .. does not apply. how can i do something like that?

I also need to store the output in a variable.

Patientes
  • 113
  • 1
  • 1
  • 7
  • I guess you are looking for something [like that](https://stackoverflow.com/questions/431684/equivalent-of-shell-cd-command-to-change-the-working-directory) – mhusna Aug 01 '22 at 18:33
  • 4
    You wouldn't use `os.system` to execute `cd` in the first place; you'd use `os.chdir`. – chepner Aug 01 '22 at 18:39

2 Answers2

0

I wouldn't use os.system to check the contents of a directory, instead use os.listdir() and os.chdir().

initial_state = os.listdir()
os.chdir("..")
one_dir_up_state = os.listdir()
Huessy
  • 111
  • 8
0

os.system function uses the current process of your running program and replaces the image of it with the "dir" program image, therefore your code after the call to the dir program will not be executed and discarded. To overcome this you can create a new process:

import os
from multiprocessing import Process


def dir():
    os.system("dir")


def dir2():
    # we can pass .. as an argument instead of running "cd ..""
    os.system("dir ..")


if __name__ == '__main__':
    p1 = Process(target=dir)
    p1.start()
    p1.join()

    p2 = Process(target=dir2)
    p2.start()
    p2.join()