-1

I want a program that, with given arguments, I'm using optpatse, changes the working directory and executes some file.

I have tried with:

subprocess.check_call(['ls'], cwd="/home")

and this works. But if I do:

subprocess.call("cd", shell=True)
subprocess.call("ls", shell=True)

This doesn't work, the "ls" shows me where the current python file is working. I understand that both commands get executed correctly, but I need the second one be executed at the directory from the first command.

def followpath(path):

    subprocess.call("cd", shell=True)
    subprocess.call("ls", shell=True)

#The real thing I want to execute is:

    subprocess.call("cd", shell=True)
    subprocess.call(["cd", path])
    subprocess.call(["python3", somepyfile])

I expect also that, after running the script in the terminal, the working directory changes to the path and the somepyfile is executed.

barbsan
  • 3,418
  • 11
  • 21
  • 28
Ajapollo Trukatila
  • 463
  • 1
  • 4
  • 12

1 Answers1

0

subprocess.call() creates a child process, your cd will therefore change the CWD of the child process (which then immediately exits). You want os.chdir(path) to change the CWD of your program.

Andrew Gelnar
  • 633
  • 4
  • 14
  • And how can I work with the child process? And now yes, it changes the dir, but when the program finishes returns to the old dir of the script file – Ajapollo Trukatila Jun 19 '19 at 10:33
  • Also worth noting that it's not possible to change the working directory of the shell running the script. When the script completes, the shell/terminal you ran it from will be where it started. – Holloway Jun 19 '19 at 10:33
  • ok, so I could open a new shell in the wanted path and execute the file with the os module? – Ajapollo Trukatila Jun 19 '19 at 10:35
  • @AjapolloTrukatila Changing the directory of the Python interpreter itself thus changes the directory of programs it starts -- so `os.chdir()` puts the Python interpreter in the right directory; and then when you start an external program, it's in that directory right off the bat. – Charles Duffy Jun 19 '19 at 12:57
  • @AndrewGelnar, please note, in [How to Answer](https://stackoverflow.com/help/how-to-answer), the section *"Answer Well-Asked Questions"*, and the bullet point therein regarding questions which "have been asked and answered many times before". – Charles Duffy Jun 19 '19 at 12:58