【问题标题】:Running a part of python code in background在后台运行部分python代码
【发布时间】:2016-08-26 14:51:49
【问题描述】:

我正在编写一个 python 脚本,它为用户提供了两个选项。在一个选项中,用户输入用于在后台运行功能。另一方面,用户输入用于在前台运行功能。我怎样才能实现两者?我不想使用“nohup”命令在后台运行完整的脚本。我只希望某个功能在后台运行。

我还希望后台进程按用户意愿停止。

这是我想做的一个小例子:

def display():
    cnt = 1
    a = []
    if len(live_matches) == 0:
        print "sorry, no live matches currently"
    else:
        for match in live_matches:
            print str(cnt) + "." + match['mchdesc'] + "," + match['mnum'] 
            a[cnt] = match
            cnt = cnt + 1
        choice = raw_input("Enter the match numbers for live updates separated by spaces")
        for c in choice.split(' '):
            update_matches.append(a[int(c)])
        if len(update_matches) > 0:
            #call some function and run in background
    cnt = 1
    for match in completed_matches:
        print str(cnt) + "." + match['mchdesc'] + "," + match['mnum'] 
        cnt = cnt + 1
    choice = raw_input("enter the match number for scorecard")
    #call some function again but run it in foreground

【问题讨论】:

  • 使用multiprocessing标准Python模块在后台运行你的函数。
  • 你的意思是异步/同步运行这些函数?
  • @danielfranca 这两个功能彼此无关。
  • 如果你在 Python3.5 上,使用@mguijarr 告诉的多处理或异步/等待

标签: python nohup


【解决方案1】:

1.threading.Thread 可能会帮助你,threading.Lock() 会锁定你的数据。

我只是有个想法,你可以使用global input data来检查用户输入,两个线程会检查它,并确定谁锁定你的输出数据,主线程将打印它,输入也可以结束两个线程。 (也许会打破while 循环)

2.await/async 是一个很好的异步IO方式,你可以使用send方法来执行原生协程函数直到yield。 也许它可以做到这一点。

希望对你有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-14
    • 2014-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-15
    • 1970-01-01
    • 2021-07-31
    相关资源
    最近更新 更多