Search code examples
pythonunixumask

Is there a way to create executable files in Python without os.chmod for *nix systems?


By default open writes files with 666 octal permission: -rw-rw-rw-. I wonder if there's a way to make open creates files with the execution bit set. For instance, if presumably my system's umask value is 0000 then any file written with open will be written with the permission -rw-rw-rw-:

$ umask 
0000 

>>> open("aaa", "w")

$ ls -l aaa
-rw-rw-rw- 1 Kuser Kuser 0 Jun 19 08:44 aaa

I'm looking for a way to set the default permission value of open to 777 octal so I can write executable files directly without os.chmod. Or generally is there a way to achieve this in Python? Probably using lower-level file processing tools from os module? touch and most editors use 666 octal permission mode by default.

I wasn't able to obtain files with the execution bit set for files created by touch command, touch uses 666 by default.

Note: this just an artificial question.


Solution

  • open accepts an opener argument that returns a file descriptor; os.open accepts a mode, which defaults to 0o777.

    import os
    
    with open("aaa", "w", opener=os.open) as f:
        ⋮