如果python代码存储在不同的位置,如何确定调用python代码的位置

时间:2016-01-26 03:44:31

标签: python

假设我正在从这个目录中调用python文件:

 $ pwd
 $ my_dir1/path1/
 $ python mydir2/path2/my_code.py

请注意,my_code.py存储在另一个目录中。 我想要做的是在my_code.py中确定它的调用位置。 即我希望它显示my_dir1/path1/

我应该在my_code.py中添加什么代码。

1 个答案:

答案 0 :(得分:2)

您正在寻找__file__全局变量。

> cat mydir2/path2/my_code.py
print __file__
> python mydir2/path2/my_code.py
mydir2/path2/my_code.py