查找当前运行文件的路径

查找当前运行文件的路径,第1张

查找当前运行文件路径

__file__
不是您要找的东西。不要使用意外的副作用

sys.argv[0]
永远脚本路径(如果事实上脚本已经调用)
-见http://docs.python.org/library/sys.html#sys.argv

__file__
当前正在执行的 文件(脚本或模块)的路径。这是 偶然
一样的,如果它是从脚本访问的脚本!如果要将诸如相对于脚本位置的资源文件定位到库中的有用 *** 作,则必须使用
sys.argv[0]

例:

C:junkso>type junksoscriptpathscript1.pyimport sys, osprint "script: sys.argv[0] is", repr(sys.argv[0])print "script: __file__ is", repr(__file__)print "script: cwd is", repr(os.getcwd())import whereutilswhereutils.show_where()C:junkso>type python26libsite-packageswhereutils.pyimport sys, osdef show_where():    print "show_where: sys.argv[0] is", repr(sys.argv[0])    print "show_where: __file__ is", repr(__file__)    print "show_where: cwd is", repr(os.getcwd())C:junkso>python26python scriptpathscript1.pyscript: sys.argv[0] is 'scriptpath\script1.py'script: __file__ is 'scriptpath\script1.py'script: cwd is 'C:\junk\so'show_where: sys.argv[0] is 'scriptpath\script1.py'show_where: __file__ is 'C:\python26\lib\site-packages\whereutils.pyc'show_where: cwd is 'C:\junk\so'


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5639621.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-16
下一篇2022-12-16

发表评论

登录后才能评论

评论列表(0条)

    保存