是否可以以编程方式将可调用的函数传递给python实例(使用不同的权限调用)

时间:2014-06-11 16:03:33

标签: python interpreter interprocess

假设我有python代码

def my_great_func(an_arg):
  a_file = open("/user/or/root/file", "w")
  a_file.write("bla")

我想维持而不注意有和没有priveleges的invokation。同时我不想用sudo调用脚本/强制使用sudo进行调用(虽然这可能是一个有条不紊的实践)或者为我的setuid解释器启用python(通常是个坏主意) ...)。现在的想法是启动python解释器的第二个实例,并通过进程/管道进行通信。为了最大限度地提高代码的可维护性,简单地将callable传递给实例(例如以subprocess.Popen开头并使用其PID寻址)就好了,就像我将它传递给multiprocess.Process一样我无法使用,因为我不能在子进程中setuid。我想像

这样的东西
# please consider this pseudo python code
pid = subprocess.Popen(["sudo", "python"]).get_pid()
thelib.pass_callable(pid, target, args)

甚至

interpreter_instance = greatlib.Python(target, args)
interpreter_instance.start()
interpreter_instance.wait()

这是否可以并且由现有的库覆盖?

1 个答案:

答案 0 :(得分:1)

一般来说,除非使用超级用户调用调用它的脚本,否则您不希望任何脚本以超级用户身份运行。这不仅是良好实践和安全编程的问题,也是程序员礼仪的问题。如果您的程序的任何部分需要使用超级用户,则在您开始该程序之前应该知道此意图。

考虑到这一点,Python thread library应该可以正常使用。