获取python .exe路径

时间:2019-02-15 20:45:02

标签: python working-directory

我用python编写了一个程序,当使用python解释器运行时,该程序可以正确运行。它从同一目录读取一些文件。为了从其他路径运行脚本,脚本会将其工作目录更改为自己的位置。

import os
abspath = os.path.realpath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)

但是当我将其打包到.exe时,这不起作用。因为运行.exe时__file__变量是"main.py"

我知道可以通过显式设置固定路径来对其进行修复:

os.chdir('/Fixed/Path')

但是有一个优雅的解决方案吗?

1 个答案:

答案 0 :(得分:0)

因此,这里的答案实际上分为两部分。要获取可执行文件的位置,可以使用

import os
import sys

exe = sys.executable
dname = os.path.dirname(exe)
os.chdir(dname)

要使用chdir到可执行文件的目录,您应该尝试类似

os.chdir(os.path.dirname(sys.executable))

或者简单地

static final Map<Gender, String> _genderImage = {
Gender.female: 'assets/images/gender_female.svg',
Gender.other: 'assets/images/gender_other.svg',
Gender.male: 'assets/images/gender_male.svg'
};
Widget icon = Padding(
    padding: EdgeInsets.only(left: _leftPadding(context)),
    child: SvgPicture.asset(
      _assetName,
      height: _iconSize(context),
      width: _iconSize(context),
    ));
相关问题