简单回答:你根据环境算出绝对路径。
你真正需要的是一些指针。您可以从标准库的不同位置收集到各种运行时和环境信息(当我想在 Windows 上部署应用程序时,它们肯定会帮助我)。
所以,首先一些一般的事情:
os.path
- 具有大量跨平台路径操作的标准库模块。你最好的朋友。“Follow the os.path”我曾经在一本书中读过。
__file__
- 当前模块的位置。
sys.executable
- 正在运行的 Python 的位置。
现在你可以从这三个来源中收集到任何你想要的东西。os.path 中的函数将帮助您绕过树:
os.path.join('path1', 'path2')
- 以跨平台方式加入路径段
os.path.expanduser('a_path')
a_path
-在用户的主目录中查找路径
os.path.abspath('a_path')
- 将相对路径转换为绝对路径
os.path.dirname('a_path')
- 获取路径所在的目录
- 还有很多很多...
所以结合这个,例如:
# script1.py
# Get the path to the script2.py in the same directory
import os
this_script_path = os.path.abspath(__file__)
this_dir_path = os.path.dirname(this_script_path)
script2_path = os.path.join(this_dir_path, 'script2.py')
print script2_path
并运行它:
ali@work:~/tmp$ python script1.py
/home/ali/tmp/script2.py
现在,对于您的具体情况,您似乎对“工作目录”和“脚本所在的目录”的概念有些混淆。这些可以相同,但也可以不同。例如,“工作目录”可以更改,因此使用它的函数有时可能会找到他们正在寻找的东西,但有时却找不到。subprocess.Popen
就是一个例子。
如果您总是绝对传递路径,您将永远不会遇到工作目录问题。