python fileinput changes permission

随声附和 提交于 2019-12-12 18:14:15

问题


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)


来源:https://stackoverflow.com/questions/1605288/python-fileinput-changes-permission

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!