如何";cd";在目录之间使用python脚本
我正在编写一个测试脚本,如果该路径被确认存在并且是一个目录,它应该从当前目录cd到一个新目录中如何";cd";在目录之间使用python脚本,python,linux,python-3.x,subprocess,Python,Linux,Python 3.x,Subprocess,我正在编写一个测试脚本,如果该路径被确认存在并且是一个目录,它应该从当前目录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]) 我的困
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])
我的困境是,我不知道如何正确地将变量传递到子流程命令,也不知道是否应该使用call或Popen。当我尝试上面的代码时,返回的错误是
没有这样的文件或目录“cd../etc/bin/”
。我需要从当前目录返回一个目录,这样我就可以输入/etc
并读取其中的一些文件。有什么建议吗?您应该使用os.chdir(目录)
,然后打电话打开您的进程。我想这将是更直接和可读的来更改使用的工作目录
os.chdir(“/your/path/here”)
子进程将生成新进程,这不会影响父进程。不可能使用子进程更改当前目录,因为这将仅在该子进程的上下文中更改当前目录,并且不会影响当前进程 相反,要更改Python进程中的当前目录,请使用Python的函数,该函数可执行以下操作:,例如:
另一方面,如果您的想法是Python脚本不做任何其他事情,只是更改目录而不是退出(这就是我对这个问题的理解),那么这也不会起作用,因为当您退出Python进程时,父进程的当前工作目录将再次不受影响。如果您想拿回一个文件夹,就像你在贝壳里做的那样
os.chdir('..')
或者在你的情况下,你可以
directory = "/etc/bin/foo"
if os.path.exists(directory) and os.path.isdir(directory):
os.path.normpath(os.getcwd() + os.sep + os.pardir)
输出将是:“/etc/bin”使用
子流程运行cd
几乎总是无用的;它只更改分叉子流程的工作目录,一旦subprocess.call
returns,当前工作目录将直接保持不变。如果您希望工作目录在Python进程退出后发生更改,这也是正确的。这不仅仅是“简单”和“可读的”:这是唯一可行的方法。在子进程中执行cd
,对父进程绝对没有影响。
directory = "/etc/bin/foo"
if os.path.exists(directory) and os.path.isdir(directory):
os.path.normpath(os.getcwd() + os.sep + os.pardir)