1

例如,这是我的目录树:

+--- test.py
|
+--- [subdir]
      |
      +--- another.py

测试.py:

import os
os.system('python subdir/another.py')

另一个.py:

import os
os.mkdir('whatever')

运行 test.py 后,我希望有一个文件夹whateversubdir但我得到的是:

+--- test.py
|
+--- [subdir]
|     |
|     +--- another.py
|
+--- whatever

原因很明显:工作目录没有更改为subdir. 那么在不同文件夹中执行 .py 文件时是否可以更改工作目录?笔记:

  1. 任何功能都是允许的,os.system只是一个例子
  2. os.system('cd XXX')并且os.chdir不允许

编辑:最后我决定使用上下文管理器,遵循
https://stackoverflow.com/posts/17589236/edit中的答案

import os
import subprocess # just to call an arbitrary command e.g. 'ls'

class cd:
    def __init__(self, newPath):
        self.newPath = newPath

    def __enter__(self):
        self.savedPath = os.getcwd()
        os.chdir(self.newPath)

    def __exit__(self, etype, value, traceback):
        os.chdir(self.savedPath)

# Now you can enter the directory like this:
with cd("~/Library"):
   # we are in ~/Library
   subprocess.call("ls")

# outside the context manager we are back where we started.
4

3 回答 3

5

您确实可以使用os.chdir但依赖于当前工作目录实际上正在寻找麻烦的假设,在您的情况下,这也适用于os.system调用test.py- 尝试test.py从其他任何地方执行,您会发现原因。

安全的方法是从属性中派生当前模块/脚本的绝对路径,并为调用in和调用in__file__构建绝对路径os.systemtest.pyos.mkdiranother.py

要获取当前模块或脚本目录的绝对路径,只需使用:

import os
ABS_PATH = os.path.dirname(os.path.abspath(__file__))
于 2013-07-11T09:16:18.870 回答
4

嗯,这是执行此操作的函数:os.chdir( path )

也许它有点令人困惑或不一致,因为获取当前工作目录的函数被调用os.getcwd()并且没有对应的设置器。尽管如此,医生说清楚地chdir改变了CWD。

在 python 3.x 中路径也可以是有效的文件描述符,而在 2.x 中fchdir(fd)必须使用分支。

于 2013-07-11T09:04:41.207 回答
2

cwd将参数传递给subprocesscall().

os.system()已过时;该subprocess模块功能更强大。

于 2013-07-11T12:02:43.860 回答