如何知道 Python 中正在运行的脚本的路径? [英] How can I know the path of the running script in Python?
本文介绍了如何知道 Python 中正在运行的脚本的路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的 script.py 在与脚本相同的目录中创建一个临时文件.
My script.py creates a temporary file in the same directory as the script.
运行时:
python script.py
效果很好.
但是运行的时候不行:
python /path/to/script.py
那是因为我在 script.py 中使用了我的临时文件的相对路径,而不是绝对路径.问题是我不知道它将在哪个路径上运行,所以我需要一种动态知道这一点的方法.
That's because I'm using a relative path to my temporary file in script.py rather than an absolute one. The problem is that I don't know in which path it will be running in, so I need a way to dynamically know this.
接下来呢?
os.path.abspath(os.path.dirname(__file__))
推荐答案
Per the great Dive进入Python:
Per the great Dive Into Python:
import sys, os
print 'sys.argv[0] =', sys.argv[0] 1
pathname = os.path.dirname(sys.argv[0]) 2
print 'path =', pathname
print 'full path =', os.path.abspath(pathname)
这篇关于如何知道 Python 中正在运行的脚本的路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文