例如,这是我的目录树:
+--- test.py
|
+--- [subdir]
|
+--- another.py
Run Code Online (Sandbox Code Playgroud)
测试.py:
import os
os.system('python subdir/another.py')
Run Code Online (Sandbox Code Playgroud)
另一个.py:
import os
os.mkdir('whatever')
Run Code Online (Sandbox Code Playgroud)
运行test.py后,我预计将有一个文件夹whatever中subdir,但我得到的是:
+--- test.py
|
+--- [subdir]
| |
| +--- another.py
|
+--- whatever
Run Code Online (Sandbox Code Playgroud)
原因很明显:工作目录没有更改为subdir.那么在不同文件夹中执行.py文件时是否可以更改工作目录?笔记:
os.system只是一个例子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.
Run Code Online (Sandbox Code Playgroud)
您确实可以使用os.chdir但依赖于当前工作目录实际上是什么的假设正在寻找问题,在您的情况下,这也适用于os.system调用test.py- 尝试test.py从其他任何地方执行,您会发现原因。
安全的方法是从__file__属性中导出当前模块/脚本的绝对路径,并为调用os.systemintest.py和调用os.mkdirin构建绝对路径another.py
要获取当前模块或脚本目录的绝对路径,只需使用:
import os
ABS_PATH = os.path.dirname(os.path.abspath(__file__))
Run Code Online (Sandbox Code Playgroud)