[英]Get path of file being run after cd to another directory in python
I have following simple script test.py
in directory /Users/apps
:- 我在
/Users/apps
目录中有以下简单脚本test.py
import os
os.chdir("/Users/apps/update/diiferent_path")
path = os.path.dirname(os.path.abspath(__file__))
print(path)
I am getting path value as /Users/apps/update/diiferent_path
because I have changed the directory. 我获取的路径值为
/Users/apps/update/diiferent_path
因为我已经更改了目录。 How can I get test.py path ie /Users/apps
after changing directory. 更改目录后,如何获取test.py路径,即
/Users/apps
。
It's impossible to do it after the chdir
(unless, of course, if __file__
already contains the absolute path), because the information is lost. 在
chdir
之后是不可能的(当然,除非__file__
已经包含绝对路径),因为信息会丢失。 There is no such thing as what was the current directory when the process started stored anywhere automatically. 进程启动时,当前目录不会自动存储在任何地方。 But you can store it manually by calling
os.path.abspath(__file__)
before calling the chdir
. 但是您可以在调用
chdir
之前通过调用os.path.abspath(__file__)
手动存储它。
I agree with pts post that storing the path is the way to go. 我同意pts的观点,即存储路径是要走的路。 It best shows your intention of getting the original path, despite what modifications are done throughout the script.
尽管在脚本中进行了一些修改,但它最好地表明了您获取原始路径的意图。
For reference sake two workarounds. 作为参考,有两种解决方法。 The path changes because the script is executed by name.
路径会更改,因为脚本是按名称执行的。 The interpreter then finds the file in the current directory.
然后,解释器在当前目录中找到文件。 The current directory changes, and thus the absolute path of both
__file__
and sys.argv
. 当前目录更改,因此
__file__
和sys.argv
的绝对路径也更改。
One way around that is to call the script with an absolute path . 解决该问题的一种方法是使用绝对路径调用脚本。 Another is to realize that the path of the script is automatically added to the PYTHONPATH , ie to
sys.path
. 另一个是要认识到脚本的路径会自动添加到PYTHONPATH中 ,即
sys.path
。 The following script illustrates that: 以下脚本说明了这一点:
#!/usr/bin/python
import os
import sys
os.chdir("/usr/bin")
print(os.path.abspath(__file__))
print(os.path.abspath(sys.argv[0]))
print(sys.path[0])
The output: 输出:
# /tmp$ ./so24323731.py
/usr/bin/so24323731.py
/usr/bin/so24323731.py
/tmp
# /tmp$ /tmp/so24323731.py
/tmp/so24323731.py
/tmp/so24323731.py
/tmp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.