0
for root, dirs, files in os.walk(rawsource):
    print("root is {}".format(root))
    try:
        os.system("cd {}".format(root))
        print("root in the try: was {}".format(root))
        print("pwd is {}".format(os.system("pwd")))

I am not sure why: os.system("cd {}".format(root)) is failing. Meaning, it doesnt appear to properly be changing directory cd to the value of root, but instead appears to be staying at /Users/user/Project

But, print("root in the try: was {}".format(root)) is properly outputting the proper directory within the loop.

This is the output:

pwd is 0
root is /Users/user/Project/src/main/gateway
root in the try: was /Users/user/Project/src/main/gateway
/Users/user/Project

Why might this be happening?

Jshee
  • 2,620
  • 6
  • 44
  • 60
  • 1
    What do you mean by failing? – Andy Dec 18 '20 at 15:57
  • See updated @Oso . Its printing only sub part of the path - see last line of output – Jshee Dec 18 '20 at 16:01
  • The output does not appear to correspond with the version of the program in the question. – Andrew Morton Dec 18 '20 at 17:21
  • 1
    For each `system` call you get a new shell. So the first `os.system("cd {}".format(root))` changes to the new directory (likely) but the second `"pwd is {}".format(os.system("pwd"))` is in a new shell that knows nothing about the first shell. – dawg Dec 18 '20 at 17:23
  • 1
    Is there a reason you are not using `os.chdir` and `os.getcwd()`? – dawg Dec 18 '20 at 17:24
  • The `0` you are seeing is simply the successful return code. So `os.system("cd {}".format(root))` does this 1) spawns a shell; 2) executes the shell function `cd` with the argument supplied 3) givens the return code of `0` meaning it was done successfully and 4) EXITS! – dawg Dec 18 '20 at 17:31
  • @dawg - chdir and getcwd were exactly what i was missing. Its been a bit of time. Thanks! – Jshee Dec 18 '20 at 17:54
  • What is the reason you want to change to a new directory? If you just want to print out file names or otherwise process the files in your python code, you should just do it directly without `os.system()`. – Code-Apprentice Dec 18 '20 at 17:57
  • @dawg I think your first comment is the actual answer here because it describes why the OP sees the behavior they are asking about. The dupe links might be answers to the Y of this XY problem. – Code-Apprentice Dec 18 '20 at 17:59

0 Answers0