对于您的启动工作目录(作为脚本的第一行之一):
ini_path = os.getcwd()
对于脚本的路径,请使用sys.path[0]。
测试代码(请在家尝试):
import sys, os, inspect
ini_path = os.getcwd()
def ppaths(d=''):
print('sys.path[0]: {}'.format(sys.path[0]))
print('ini_path: {}'.format(ini_path))
print('os.getcwd: {}'.format(os.getcwd()))
print('inspect.getfile: {}'.format(inspect.getfile(inspect.currentframe())))
print('os.dirfile: {}'.format(
os.path.dirname(inspect.getfile(inspect.currentframe()))))
if d:
print('==== Changing to "{}" '.format(d))
os.chdir(d)
print()
ppaths('/')
ppaths('Users')
ppaths()
在我的系统上(从编辑器内部运行),打印:
sys.path[0]: /private/var/folders/00/kbqj5nt54m99z5gyffy8fksm0000gp/T/Cleanup At Startup
ini_path: /Users/andrew
os.getcwd: /Users/andrew
inspect.getfile: /private/var/folders/00/kbqj5nt54m99z5gyffy8fksm0000gp/T/Cleanup At Startup/untitled text 3-367027656.416
os.dirfile: /private/var/folders/00/kbqj5nt54m99z5gyffy8fksm0000gp/T/Cleanup At Startup
==== Changing to "/"
sys.path[0]: /private/var/folders/00/kbqj5nt54m99z5gyffy8fksm0000gp/T/Cleanup At Startup
ini_path: /Users/andrew
os.getcwd: /
inspect.getfile: /private/var/folders/00/kbqj5nt54m99z5gyffy8fksm0000gp/T/Cleanup At Startup/untitled text 3-367027656.416
os.dirfile: /private/var/folders/00/kbqj5nt54m99z5gyffy8fksm0000gp/T/Cleanup At Startup
==== Changing to "Users"
sys.path[0]: /private/var/folders/00/kbqj5nt54m99z5gyffy8fksm0000gp/T/Cleanup At Startup
ini_path: /Users/andrew
os.getcwd: /Users
inspect.getfile: /private/var/folders/00/kbqj5nt54m99z5gyffy8fksm0000gp/T/Cleanup At Startup/untitled text 3-367027656.416
os.dirfile: /private/var/folders/00/kbqj5nt54m99z5gyffy8fksm0000gp/T/Cleanup At Startup
现在,从 Bash 运行它:
kitchen:SO andrew$ pwd
/Users/andrew/bin/SO
kitchen:SO andrew$ ls ins.py
ins.py
kitchen:SO andrew$ ./ins.py
sys.path[0]: /Users/andrew/bin/SO
ini_path: /Users/andrew/bin/SO
os.getcwd: /Users/andrew/bin/SO
inspect.getfile: ./ins.py
os.dirfile: .
==== Changing to "/"
sys.path[0]: /Users/andrew/bin/SO
ini_path: /Users/andrew/bin/SO
os.getcwd: /
inspect.getfile: ./ins.py
os.dirfile: .
==== Changing to "Users"
sys.path[0]: /Users/andrew/bin/SO
ini_path: /Users/andrew/bin/SO
os.getcwd: /Users
inspect.getfile: ./ins.py
os.dirfile: .
kitchen:SO andrew$
从 Bash 中的不同目录运行:
kitchen:SO andrew$ cd ..
kitchen:bin andrew$ ./SO/ins.py
sys.path[0]: /Users/andrew/bin/SO
ini_path: /Users/andrew/bin
os.getcwd: /Users/andrew/bin
inspect.getfile: ./SO/ins.py
os.dirfile: ./SO
==== Changing to "/"
sys.path[0]: /Users/andrew/bin/SO
ini_path: /Users/andrew/bin
os.getcwd: /
inspect.getfile: ./SO/ins.py
os.dirfile: ./SO
==== Changing to "Users"
sys.path[0]: /Users/andrew/bin/SO
ini_path: /Users/andrew/bin
os.getcwd: /Users
inspect.getfile: ./SO/ins.py
os.dirfile: ./SO
在所有情况下,sys.path[0]
指向启动脚本的绝对路径。
为了os.getcwd()
开始工作,您可以看到您还必须解析脚本名称的前导路径 - 更多工作......
更多在这个 SO 帖子中。