如何知道Python中正在运行的脚本的路径? [英] How to know the path of the running script in Python?
本文介绍了如何知道Python中正在运行的脚本的路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的script.py在与脚本相同的目录中创建一个临时文件.
My script.py creates a temporary file in the same dir as the script.
运行时:
python script.py
仅适用于文件
但运行时不起作用:
python /path/to/script.py
那是因为我在script.py中使用了我的临时文件的相对路径,而不是绝对路径.问题是我不知道它将在哪条路径中运行,因此我需要一种方法来明确地知道这一点.
That's because I'm using a relative path to my temp 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 dinamicaly know this.
那是什么?
os.path.abspath(os.path.dirname(__file__))
推荐答案
根据出色的潜水进入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屋!
查看全文