How to set shortcut working directory in cx_freeze

2019-02-11 05:59发布

问题:

I was working on a Python program which deals with SQLite3 databases. I made it as an MSI setup file by using cx_Freeze.

Windows shortcuts produced by .msi set-up files generated by cx_Freeze do not provide the working directory property of the shortcut. Thus, when I run the executable using the shortcut created on the desktop, it's creating database files on the desktop itself.

This can be changed by providing a different working directory to the shortcut. How do I do that?

回答1:

I was able to fix the problem by making a small change to cx_Freeze/windist.py. In add_config(), line 61, I changed:

msilib.add_data(self.db, "Shortcut",
        [("S_APP_%s" % index, executable.shortcutDir,
                executable.shortcutName, "TARGETDIR",
                "[TARGETDIR]%s" % baseName, None, None, None,
                None, None, None, None)])

to

msilib.add_data(self.db, "Shortcut",
        [("S_APP_%s" % index, executable.shortcutDir,
                executable.shortcutName, "TARGETDIR",
                "[TARGETDIR]%s" % baseName, None, None, None,
                None, None, None, "TARGETDIR")]) # <--- Working directory.

Thanks everyone.



回答2:

Found the solution in the answer to another question. Essentially, one needs to set up the shortcut table data. The last 'TARGETDIR' in the shortcut_table below sets up the working directory to be the installation directory.

---copied from above mentioned answer---

from cx_Freeze import *

# http://msdn.microsoft.com/en-us/library/windows/desktop/aa371847(v=vs.85).aspx
shortcut_table = [
    ("DesktopShortcut",        # Shortcut
     "DesktopFolder",          # Directory_
     "DTI Playlist",           # Name
     "TARGETDIR",              # Component_
     "[TARGETDIR]playlist.exe",# Target
     None,                     # Arguments
     None,                     # Description
     None,                     # Hotkey
     None,                     # Icon
     None,                     # IconIndex
     None,                     # ShowCmd
     'TARGETDIR'               # WkDir
     )
    ]

# Now create the table dictionary
msi_data = {"Shortcut": shortcut_table}

# Change some default MSI options and specify the use of the above defined tables
bdist_msi_options = {'data': msi_data}

setup(
    options = {
        "bdist_msi": bdist_msi_options,
    },
    executables = [
        Executable(
            "MyApp.py",
            )
        ]
    )