如何获取执行冻结脚本的路径

编程入门 行业动态 更新时间:2024-10-28 19:24:50
本文介绍了如何获取执行冻结脚本的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

如果您从与脚本所在的目录和驱动器不同的目录和驱动器运行冻结的 python 脚本(使用 py2exe 冻结),确定执行脚本的路径的最佳方法是什么?

If you are running a frozen python script (frozen using py2exe) from a directory and drive different from where the script is present, what is the best way to determine the path of the executing script?

我尝试过的几种解决方案

Few solutions I have tried

inspect.getfile(inspect.currentframe())

问题:不返回完整路径.它只返回脚本名称.

os.path.abspath( __file__ )

问题:不适用于 Windows

os.path.dirname(sys.argv[0])

问题:返回空字符串.

os.path.abspath(inspect.getsourcefile(way3))

如果驱动器与密码不同将不起作用

os.path.dirname(os.path.realpath(sys.argv[0]))

如果驱动器与密码不同将不起作用

这是一个最小的不工作示例

Here is a minimal not-working example

D:\>path
PATH=c:\Python27\;c:\Users\abhibhat\Desktop\ToBeRemoved\spam\dist\;c:\gnuwin32\bin

D:\>cat c:\Users\abhibhat\Desktop\ToBeRemoved\spam\eggs.py
import os, inspect, sys
def way1():
    return os.path.dirname(sys.argv[0])

def way2():
    return inspect.getfile(inspect.currentframe())

def way3():
    return os.path.dirname(os.path.realpath(sys.argv[0]))

def way4():
    try:
        return os.path.abspath( __file__ )
    except NameError:
        return "Not Found"
def way5():
    return os.path.abspath(inspect.getsourcefile(way3))

if __name__ == '__main__':
    print "Path to this script is",way1()
    print "Path to this script is",way2()
    print "Path to this script is",way3()
    print "Path to this script is",way4()
    print "Path to this script is",way5()

D:\>eggs
Path to this script is
Path to this script is eggs.py
Path to this script is D:\
Path to this script is Not Found

相关问题:

如何知道在 Python 中运行脚本?如何获取当前正在执行的文件的路径和名称?python,脚本路径[关闭]

注意

@Fenikso 的解决方案如果脚本驻留在您正在执行的同一驱动器上将起作用,但是当它在不同的驱动器上时,它将不起作用

@Fenikso's solution will work if the script resides on the same drive where you are executing but when its on a different drive, it will not work

推荐答案

当从另一个驱动器运行时,即使使用 PATH 也能与 cxFreeze 一起使用的另一种方法:

Another approach which works with cxFreeze when running from another drive even using PATH:

import sys

if hasattr(sys, 'frozen'):
    print(sys.executable)
else:
    print(sys.argv[0])

来自 Python:

H:\Python\Examples\cxfreeze\pwdme.py

从命令行:

D:\>h:\Python\Examples\cxfreeze\dist\pwdme.exe
h:\Python\Examples\cxfreeze\dist\pwdme.exe

使用路径:

D:\>pwdme.exe
h:\Python\Examples\cxfreeze\dist\pwdme.exe

这篇关于如何获取执行冻结脚本的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-16 17:34:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/892972.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:脚本   路径

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!