python fileinput changes permission

2019-07-19 17:49发布

问题:

In my python code, I use the fileinput module for inplace replacing:

import fileinput

for line in fileinput.FileInput("permission.txt",inplace=1):
    line = line.strip()
    if not 'def' in line:
        print line
    else:
        line=line.replace(line,'zzz')
        print line


fileinput.close()

However, once it is done, permission.txt permissions is now changed to root only access. I can no longer edit the file. I can only delete it.

I did some googling and it mentioned that this could be caused because fileinput creates a temporary file for this read/write replace interaction.

However, I would have thought there would be a fix for this since the bug was reported in 1999. Is it something I have to do in my code to keep the permissions the same? or is it an operating system level issue.

I'm using Python 2.6.2 on Ubuntu 9.04

回答1:

If you can help it, don't run your script as root.

EDIT Well, the answer has been accepted, but it's not really much of an answer. In case you must run the script as root (or indeed as any other user), you can use os.stat() to determine the user id and group id of the file's owner before processing the file, and then restore the file ownership after processing.

import fileinput
import os

# save original file ownership details
stat = os.stat('permission.txt')
uid, gid = stat[4], stat[5]

for line in fileinput.FileInput("permission.txt",inplace=1):
    line = line.strip()
    if not 'def' in line:
        print line
    else:
        line=line.replace(line,'zzz')
        print line


fileinput.close()

# restore original file ownership
os.chown("permission.txt", uid, gid)