python文件输入更改权限 [英] python fileinput changes permission

查看:681
本文介绍了python文件输入更改权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 导入文件输入
$ b $在我的python代码中,我使用fileinput模块进行替换: b为fileinput.FileInput(permission.txt,inplace = 1)中的行:
line = line.strip()
如果不是'def'行:
print line
$ else $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ code>

但是,一旦完成,permission.txt权限现在更改为root only权限。我不能再编辑文件。我只能删除它。



我做了一些搜索,它提到,这可能是由于fileinput创建一个临时文件这个读/写替换交互。 >

然而,我想会有一个解决方案,因为这个bug是在1999年报告的。在我的代码中,我必须做的事情是保持权限不变吗?或者是操作系统级别的问题。



我在Ubuntu 9.04上使用Python 2.6.2

解决方案

如果您可以提供帮助,请不要以超级用户身份运行您的脚本。
$ b

编辑 $ b那么答案已经被接受了,但这不是一个真正的答案。如果您必须以root用户身份运行脚本(或者其他任何用户),您可以使用 os.stat() 在处理文件之前确定文件所有者的用户标识和组标识,然后在处理之后恢复文件所有权。

$ p $ 导入文件输入
导入操作系统

#保存原始文件所有权的详细信息
stat = os.stat('permission.txt')
uid,gid = stat [4],stat [5]

for fileinput.FileInput(permission.txt ,inplace = 1):
line = line.strip()
如果不是'def'行:
print line
else:
line = line.replace (line,'zzz')
print line


fileinput.close()

#恢复原始文件所有权
os.chown (permission.txt,uid,gid)


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

解决方案

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)

这篇关于python文件输入更改权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆