使用python装饰器进行身份验证
我一直在尝试学习python装饰器,并编写了以下代码。但它总是出错使用python装饰器进行身份验证,python,Python,我一直在尝试学习python装饰器,并编写了以下代码。但它总是出错 import os import sys def authenticate(fn): def wrapper(*args): euid = os.geteuid() if euid != 0: print "This command requires privliged mode. Enter password.." args = ['su
import os
import sys
def authenticate(fn):
def wrapper(*args):
euid = os.geteuid()
if euid != 0:
print "This command requires privliged mode. Enter password.."
args = ['sudo', sys.executable] + sys.argv + [os.environ]
os.execlpe('sudo', *args)
fn(*args)
return wrapper
@authenticate
def show_files(dir):
files = [f for f in os.listdir(dir)]
for file in files:
if os.path.isfile(file):
print file
dir = raw_input("Please enter a directory name\t")
show_files(dir)
我得到以下回溯:
Traceback (most recent call last):
File "auth1.py", line 24, in show_files(dir)
File "auth1.py", line 11, in wrapper fn(*args)
File "auth1.py", line 16, in show_files files = [f for f in os.listdir(dir)]
OSError: [Errno 2] No such file or directory: ''
这样做的目的是只对能够进行身份验证的用户运行
show_files
功能。我的问题似乎是编写身份验证的方式和execlpe
调用。非常感谢您的帮助。您知道问题是出在decorator语法还是execlpe/sudo部分吗?试着一次解决其中一个挑战。不过,你的装饰程序看起来不错,除非我遗漏了什么——我没有尝试运行代码
祝你好运
Uli以下代码工作正常。感谢那些以有帮助的方式回复的人 !/usr/bin/python 导入操作系统 导入系统 def身份验证(fn): @鉴定 def show_files():
show_files()您需要显示实际完整的错误消息。您在提示符处输入的目录是什么?我输入了/tmp。我想问题出在行政电话上。我不认为我完全理解它。dir和*args最终是一样的吗?对这种奇怪的编程方法投反对票。Sudo在脚本外,但不在脚本内…这让我哭了。为什么要覆盖args?
def wrapper():
euid = os.geteuid()
if euid != 0:
print "This command requires privliged mode. Enter password.."
os.execvp("sudo", ["sudo"] + sys.argv)
fn()
return wrapper
dir = raw_input("Please enter a directory name\t")
files = [f for f in os.listdir(dir)]
for file in files:
if os.path.isfile(file):
print file