Python 모듈 os.chmod 제대로 사용하기
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
이번 문제는 chmod 사용 중 권한을 주기 위해 10진법으로 매개변수를 전달하여, 오작동한 경우입니다.
실제 문제와 자세한 설명은 아래를 참고해주세요.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
Python module os.chmod(file, 664) does not change the permission to rw-rw-r-- but -w--wx----
Python 모듈 os.chmod(file, 664)은 권한을 rw-rw-r--으로 변경하지 않고 -w--wx----으로 변경됩니다.
문제 내용
Recently I am using Python module os, when I tried to change the permission of a file, I did not get the expected result. For example, I intended to change the permission to rw-rw-r--,
최근에 저는 Python 모듈인 os를 사용 중이었는데, 파일의 권한을 변경하려고 시도했지만 원하는 결과를 얻지 못했습니다. 예를 들어, 저는 rw-rw-r-- 권한으로 변경하려 했는데,
os.chmod("/tmp/test_file", 664)
The ownership permission is actually -w--wx--- (230)
실제 소유 권한은 -w--wx--- (230)입니다.
--w--wx--- 1 ag ag 0 Mar 25 05:45 test_file
However, if I change 664 to 0664 in the code, the result is just what I need, e.g.
하지만, 코드에서 664를 0664로 변경하면, 필요한 대로 결과가 출력됩니다. 예를 들어,
os.chmod("/tmp/test_file", 0664)
The result is:
결과는 다음과 같습니다:
-rw-rw-r-- 1 ag ag 0 Mar 25 05:55 test_file
Could anybody help explaining why does that leading 0 is so important to get the correct result?
올바른 결과를 얻기 위해 0으로 시작하는게 왜 그렇게 중요한지 설명하는 데 도움을 줄 수 있는 사람이 있을까요?
높은 점수를 받은 Solution
Found this on a different forum
다른 포럼에서 이걸 찾았습니다.
If you're wondering why that leading zero is important, it's because permissions are set as an octal integer, and Python automagically treats any integer with a leading zero as octal. So os.chmod("file", 484) (in decimal) would give the same result.
만약 어떤 이유로 앞에 0이 붙는 것이 중요하다고 궁금하다면, 이것은 권한(permission)이 8진법 정수로 설정되기 때문이며, Python은 자동으로 앞에 0이 붙은 정수를 8진법으로 취급하기 때문입니다. 그래서 os.chmod("file", 484) (10진법)는 동일한 결과를 제공합니다.
What you are doing is passing 664
which in octal is 1230
당신이 하는 일은 664를 전달하는 것입니다. 8진수로는 1230입니다.
In your case you would need
당신의 경우에는 다음이 필요합니다.
os.chmod("/tmp/test_file", 436)
[Update] Note, for Python 3 you have prefix with 0o (zero oh). E.G, 0o666
[업데이트] Python 3의 경우 접두어로 0o (제로 오)를 사용해야 합니다. 예를 들면, 0o666입니다.
가장 최근 달린 Solution
@mc.dev's answer was the best answer here I ended up leveraging that to make the below function wrapper for reuse. Thanks for the share.
@mc.dev의 답변이 여기서 가장 좋은 답변이었고, 나는 그것을 재사용을 위한 아래 함수 래퍼를 만드는 데 활용했다. 공유해 줘서 고마워.
def chmod_digit(file_path, perms):
"""
Helper function to chmod like you would in unix without having to preface 0o or converting to octal yourself.
Credits: https://stackoverflow.com/a/60052847/1621381
"""
os.chmod(file_path, int(str(perms), base=8))
출처 : https://stackoverflow.com/questions/15607903/python-module-os-chmodfile-664-does-not-change-the-permission-to-rw-rw-r-bu