0

EDIT: I have found that the problem is not with this code, it is actually a simple problem later on that acts in a similar fashion to shown here.

I'm making a program that performs different stages of compression on a file. This part of the code compresses to ZIP, then DMG and then renames the file to one extension. It does this in the temp/ directory.

My code:

from os import system as sysCmd
from os import rename, remove
import zipfile

...

# STEP 3 - create a zipfile
zip = zipfile.ZipFile(workDir + filename + ".zip", mode='w')
zip.write(workDir + filename + ".datei")
zip.close()

# STEP 4 - Compress to a DMG - THE PROBLEM IS HERE
sysCmd("hdiutil create -fs MS-DOS " + workDir + filename + ".dmg -srcfolder " + workDir + filename + ".zip")  # there is no more pythonesque way :(

# STEP 5  - Rename to  *.datei
remove(workDir + filename + ".datei")  # remove pre-existing datei
rename(workDir + filename + ".dmg", workDir + filename + ".datei")

The problem:

It creates a zip temp/myFile.zip but not a DMG from the zip temp/myFile.dmg.

I'm of course getting the error from os.rename because the file doesn't exist:

created: /path/to/files/temp/README.dmg
Traceback (most recent call last):
  File "datei.py", line 59, in <module>
    rename(workDir + filename + ".dmg", workDir + filename + ".datei")
FileNotFoundError: [Errno 2] No such file or directory: '/path/to/files/temp/README.dmg' -> '/path/to/files/temp/README.datei'

What I've tried:

  • Running hidutil myself at the command line. It succeeds! This makes me wonder if the problem is with os.system().
  • Running print(os.system("ls -al " + workDir)). This tells me that there IS a file whatever.dmg even though checking with anything else denies it. Also, it tells me the rename succeeded even though that also doesn't appear anywhere else.

Help would be hugely appreciated, thanks.

1 Answers1

1

You've probably got some mixup about where the file is created, what name it has and such. E.g. if your path has spaces, the command line will be interpreted incorrectly 'cuz you don't do any quoting or escaping for the shell.

A reliable way to work with external commands in Python is to use the subprocess module and construct argv yourself 'cuz you typically don't need the shell interfering. Always check the program's exit code.

import subprocess
subprocess.check_call(("hdiutil","create",
        "-fs","MS-DOS",
        os.path.join(workDir, filename + ".dmg"),
        "-srcfolder", os.path.join(workDir, filename + ".zip")))

assert os.path.isfile(os.path.join(workDir, filename + ".dmg"))
ivan_pozdeev
  • 33,874
  • 19
  • 107
  • 152