Execute Commands Sequentially in Python?

前端 未结 5 1922
猫巷女王i
猫巷女王i 2020-12-03 07:33

I would like to execute multiple commands in a row:

i.e. (just to illustrate my need):

cmd (the shell)

then

cd dir<

5条回答
  •  眼角桃花
    2020-12-03 08:09

    Yes, the subprocess.Popen() function supports a cwd keyword argument, with which you can set the directory it runs the process in.

    I guess the first step, the shell, is not needed, if all you want is to run ls, there's no need to run it through a shell.

    Of course, you could also just pass the desired directory as an argument to ls.

    Update: it might be worth noting that for typical shells, cd is implemented in the shell itself, it is not an external command on disk. This is because it needs to change the process' current directory, which must be done from within the process. Since commands run as child processed, spawned by the shell, they cannot do this.

提交回复
热议问题