草庐IT

python - 在线程中执行 Twisted reactor.run()?

coder 2023-08-25 原文

我正在尝试制作一个 Python 库以使用来自 Objective-C 的 Ubutu One API。这是我的源代码: https://github.com/JoseExposito/U1-Finder-Plugin/blob/master/U1FinderLib/U1FinderLib.py

我需要对 API 进行多次调用,因此我需要让我的 react 器运行一次而不是运行它然后停止它,就像 Ubuntu One 文档的示例中那样: https://one.ubuntu.com/developer/files/store_files/syncdaemontool

因为不可能运行两次 react 堆...而且我需要在线程中执行 reactor.run() 因为我不能阻止使用该库的应用程序!

这有可能吗?我无法在线程中运行 react 器并同步调用 Ubuntu One API。

编辑:

我正在使用这个简单的源代码来测试这个想法:

#!/usr/bin/env python
import objc
import thread
import os
import time
from   twisted.internet import reactor, defer
from   ubuntuone.platform.tools import (SyncDaemonTool, is_already_running)
from   threading import Thread
NSObject = objc.lookUpClass('NSObject')

##
# Variable to get the result of the calls to the Sync Daemon.
# The result is a JSON string stored in returned_value[0].
returned_value = ['']

##
# Objective-C facade to the methods of the U1FinderLib.
class U1FinderLib(NSObject):

    def init(self):
        self = super(U1FinderLib, self).init()
        self.sync_daemon_tool = SyncDaemonTool(None)
        Thread(target=reactor.run, args=(False,)).start()
        return self

    @objc.typedSelector('@@:')
    def volumeList(self):
        print "Begin volumeList"
        reactor.callLater(0, run_command, "volume_list", [], self.sync_daemon_tool)
        print "End volumeList"
        return returned_value[0]

##
# Auxiliar functions to call to the sync daemon.
@defer.inlineCallbacks
def run_command(action, params, sync_daemon_tool):
    print "run_command"
    running = yield is_already_running()
    print "After is_already_running"
    try:
        if not running:
            returned_value[0] = '{ type:"error" reason:"Sync Daemon is not running" }'
        else:
            print "Before run_action"
            yield run_action(action, params, sync_daemon_tool)
            print "After run_action"
    except Exception, e:
        returned_value[0] = '{ type:"error" reason:"Exception: %s" }' % e

@defer.inlineCallbacks
def run_action(action, params, sync_daemon_tool):
    if action == "volume_list":
        d = sync_daemon_tool.get_folders()
        returned_value[0] = yield d.addCallback(lambda r: volume_list(r))

# Volume List
def volume_list(folders):
    volumes_json = '{ type:"volume_list" volumes: { \n\t{ volume:"' + os.path.expanduser('~/Ubuntu One') + '" subscribed:"YES" }'
    for folder in folders:
        volumes_json += ',\n\t{ volume:"' + folder['path'] + '" subscribed:"' + ('YES' if bool(folder['subscribed']) else 'NO') + '" }'
    volumes_json += '\n} }'
    return volumes_json

if __name__ == '__main__':
    py = U1FinderLib.alloc().init()
    print py.volumeList()
    print "EXIT"

这是程序的输出:

Begin volumeList
End volumeList

EXIT

问题是“run_command”函数从未被调用

最佳答案

与其在线程中运行 react 器,不如使用与要在其中使用它的应用程序集成的 react 器。

例如,您可能想使用 CoreFoundation reactor (因为您的应用程序使用 Obj-C 并且名称中包含“Finder”)。

如果你真的做不到(例如,如果 Ubuntu One 需要一个不同的 react 器——我不知道是否是这种情况),那么你可能可以在一个线程中运行那个 react 器。大多数 react 器都支持这一点,但如果 Ubuntu One 需要特定的 react 器,则该 react 器可能不支持线程使用。

您实际上并没有解释尝试在线程中运行 react 器时遇到的问题,所以我无法帮助您理解为什么它不起作用。但是,这样做应该很容易。只是:

from twisted.internet import reactor
from threading import Thread

Thread(target=reactor.run, args=(False,)).start()

请记住,一旦您选择在一个线程中运行 react 堆,您可以那个线程中使用 Twisted API。

如果这不起作用,请在您的问题中提供有关它为何不起作用的更多详细信息。

关于python - 在线程中执行 Twisted reactor.run()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14274916/

有关python - 在线程中执行 Twisted reactor.run()?的更多相关文章

  1. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  2. ruby-openid:执行发现时未设置@socket - 2

    我在使用omniauth/openid时遇到了一些麻烦。在尝试进行身份验证时,我在日志中发现了这一点:OpenID::FetchingError:Errorfetchinghttps://www.google.com/accounts/o8/.well-known/host-meta?hd=profiles.google.com%2Fmy_username:undefinedmethod`io'fornil:NilClass重要的是undefinedmethodio'fornil:NilClass来自openid/fetchers.rb,在下面的代码片段中:moduleNetclass

  3. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

  4. ruby - Chef 执行非顺序配方 - 2

    我遵循了教程http://gettingstartedwithchef.com/,第1章。我的运行list是"run_list":["recipe[apt]","recipe[phpap]"]我的phpapRecipe默认Recipeinclude_recipe"apache2"include_recipe"build-essential"include_recipe"openssl"include_recipe"mysql::client"include_recipe"mysql::server"include_recipe"php"include_recipe"php::modul

  5. ruby - 为什么 Ruby 的 each 迭代器先执行? - 2

    我在用Ruby执行简单任务时遇到了一件奇怪的事情。我只想用每个方法迭代字母表,但迭代在执行中先进行:alfawit=("a".."z")puts"That'sanalphabet:\n\n#{alfawit.each{|litera|putslitera}}"这段代码的结果是:(缩写)abc⋮xyzThat'sanalphabet:a..z知道为什么它会这样工作或者我做错了什么吗?提前致谢。 最佳答案 因为您的each调用被插入到在固定字符串之前执行的字符串文字中。此外,each返回一个Enumerable,实际上您甚至打印它。试试

  6. Python 相当于 Perl/Ruby ||= - 2

    这个问题在这里已经有了答案:关闭10年前。PossibleDuplicate:Pythonconditionalassignmentoperator对于这样一个简单的问题表示歉意,但是谷歌搜索||=并不是很有帮助;)Python中是否有与Ruby和Perl中的||=语句等效的语句?例如:foo="hey"foo||="what"#assignfooifit'sundefined#fooisstill"hey"bar||="yeah"#baris"yeah"另外,类似这样的东西的通用术语是什么?条件分配是我的第一个猜测,但Wikipediapage跟我想的不太一样。

  7. ruby - 检查是否通过 require 执行或导入了 Ruby 程序 - 2

    如何检查Ruby文件是否是通过“require”或“load”导入的,而不是简单地从命令行执行的?例如:foo.rb的内容:puts"Hello"bar.rb的内容require'foo'输出:$./foo.rbHello$./bar.rbHello基本上,我想调用bar.rb以不执行puts调用。 最佳答案 将foo.rb改为:if__FILE__==$0puts"Hello"end检查__FILE__-当前ruby​​文件的名称-与$0-正在运行的脚本的名称。 关于ruby-检查是否

  8. java - 什么相当于 ruby​​ 的 rack 或 python 的 Java wsgi? - 2

    什么是ruby​​的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht

  9. 华为OD机试用Python实现 -【明明的随机数】 2023Q1A - 2

    华为OD机试题本篇题目:明明的随机数题目输入描述输出描述:示例1输入输出说明代码编写思路最近更新的博客华为od2023|什么是华为od,od薪资待遇,od机试题清单华为OD机试真题大全,用Python解华为机试题|机试宝典【华为OD机试】全流程解析+经验分享,题型分享,防作弊指南华为o

  10. python - 如何读取 MIDI 文件、更改其乐器并将其写回? - 2

    我想解析一个已经存在的.mid文件,改变它的乐器,例如从“acousticgrandpiano”到“violin”,然后将它保存回去或作为另一个.mid文件。根据我在文档中看到的内容,该乐器通过program_change或patch_change指令进行了更改,但我找不到任何在已经存在的MIDI文件中执行此操作的库.他们似乎都只支持从头开始创建的MIDI文件。 最佳答案 MIDIpackage会为您完成此操作,但具体方法取决于midi文件的原始内容。一个MIDI文件由一个或多个音轨组成,每个音轨是十六个channel中任何一个上的

随机推荐