如果函数

时间:2018-04-13 20:29:31

标签: python daemon function-calls python-daemon

我试图使用python-daemon库来生成一个将写入文件的守护进程。

当我直接在"中创建守护进程时,如果__name__ ==' __ main __'"语句,守护程序成功写入文件:

from daemon import DaemonContext
def main():
    my_file.write("Daemon creation was successful")
    my_file.close()

if __name__ == "__main__":
    my_file = open("my_file", "w+")
    with DaemonContext(files_preserve=[my_file.fileno()]):
        main()

但是,当我使用单独的函数创建守护进程时,该守护进程会写入该文件:

from daemon import DaemonContext
def main():
    my_file.write("Daemon creation was successful")
    my_file.close()

def create_daemon():
    my_file = open("my_file", "w+")
    with DaemonContext(files_preserve=[my_file.fileno()]):
        main()

if __name__ == "__main__":
    create_daemon()

工作示例中的if语句和" create_daemon"非工作示例中的函数共享完全相同的代码。那么,为什么我无法通过调用函数创建一个守护进程?

2 个答案:

答案 0 :(得分:3)

这与守护进程无关。 c = 105.06 +105.06*0.04 = 109.2624 无法访问main;你没有把这个文件作为参数或任何东西传递。

答案 1 :(得分:0)

在第二个示例中,public class User { [Key] public int Id { get; set; } //...... public virtual List<Post> Posts { get; set; } public virtual List<Comment> Comments { get; set; } public virtual List<PostLikes> PostLikes { get; set; } public virtual List<CommentLIkes> CommentLikes { get; set; } } public class Post { [Key] public int Id { get; set; } public string Title { get; set; } public virtual List<PostLike> PostLikes { get; set; } public virtual List<Comment> Comments { get; set; } } public class Comment { [Key] public int Id { get; set; } public string CommentBody { get; set; } //..... public virtual List<CommentLike> CommentLikes { get; set; } } public class PostLike { [Key] public int Id { get; set; } public int PostId { get; set; } public int UserId {get; set;} public bool IsLike { get; set; } public virtual Post post { get; set; } public virtual User User { get; set; } } public class CommentLike { [Key] public int Id { get; set; } public int CommentId { get; set; } public int UserId {get; set;} public bool IsLike { get; set; } public virtual Comment Comment { get; set; } public virtual User User { get; set; } } 函数引用了不在该函数范围内的main

my_file

(如果您的示例完整)该函数将为def main(): my_file.write("Daemon creation was successful") my_file.close() 名称引发NameError

一种纠正方法是将my_file设置为my_file的参数。