如何使用 python 脚本在目录之间“cd”

pja*_*no1 0 python linux subprocess python-3.x

我正在编写一个测试脚本,如果确认该路径存在并且是一个目录,则该脚本应该从当前目录 cd 到新目录

serial_number = input("Enter serial number: ")
directory = "/etc/bin/foo"
if os.path.exists(directory) and os.path.isdir(directory):
   #cd into directory?
   subprocess.call(['cd ..' + directory])
Run Code Online (Sandbox Code Playgroud)

我的困境是我不知道如何正确地将变量传递到子进程命令中,或者是否应该使用 call 或 Popen。当我尝试上面的代码时,它返回一个错误,指出No such file or directory "cd ../etc/bin/". 我需要从当前目录返回一个目录,这样我就可以输入/etc并读取其中的一些文件。有什么建议吗?

小智 6

更改使用的工作目录

os.chdir("/your/path/here")
Run Code Online (Sandbox Code Playgroud)

子进程将产生新进程,这不会影响您的父进程。