9

凍結されたPythonスクリプト(py2exeを使用して凍結された)をディレクトリから実行していて、スクリプトが存在する場所とは異なるドライブを実行している場合、実行中のスクリプトのパスを決定する最良の方法は何ですか?

私が試したいくつかの解決策

inspect.getfile(inspect.currentframe())

問題:フルパスが返されません。スクリプト名のみを返します。

os.path.abspath( __file__ )

問題:Windowsでは動作しません

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

問題:空の文字列を返します。

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

ドライブがpwdと異なる場合は機能しません

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

ドライブがpwdと異なる場合は機能しません

これは最小限の機能しない例です

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

関連する質問:

ノート

@Feniksoのソリューションは、スクリプトが実行しているのと同じドライブにある場合は機能しますが、別のドライブにある場合は機能しません。

4

3 に答える 3

12

PATHを使用しても別のドライブから実行するときにcxFreezeで機能する別のアプローチ:

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
于 2012-04-24T08:36:24.763 に答える
2

IMHO、絶対パスに応じて動作が異なるコードは、適切なソリューションではありません。おそらく相対パスソリューションの方が良いでしょう。dirnameを使用して相対ディレクトリを確認し、os.sepを使用してクロスプラットフォームの互換性を確認します。

if hasattr(sys, "frozen"):
    main_dir = os.path.dirname(sys.executable)
    full_real_path = os.path.realpath(sys.executable)
else:
    script_dir = os.path.dirname(__file__)
    main_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
    full_real_path = os.path.realpath(sys.argv[0])

凍結された属性はPython標準です。

Eskyもご覧ください:http: //pypi.python.org/pypi/esky

于 2012-04-24T10:40:47.547 に答える
0

これを試して:

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

これは、.exe が実際に実行されている場所からディレクトリを取得するために cx_Freeze で使用するものです。

于 2012-04-24T07:57:10.993 に答える