Skip to main content
 首页 » 编程设计

python之为什么 trollius 不让这个循环异步运行

2025年05月04日8java哥

我正在尝试编写一些简单的循环来控制 Pygazebo 中的对象,但可惜它只调用一次该方法,然后循环似乎阻塞了。

# -*- coding: utf-8 -*- 
""" 
Created on Thu Jul  2 12:52:50 2015 
 
@author: skylion 
""" 
 
import trollius #NOTE: Trollius requires protobuffer from Google 
from trollius import From 
 
import pygazebo 
import pygazebo.msg.joint_cmd_pb2 
import time    
 
def apply_joint_force(world_name, robot_name, joint_name, force, duration=-1): 
 
 
    @trollius.coroutine  
    def joint_force_loop(): 
        manager = yield From(pygazebo.connect()) 
        print("connected") 
 
 
        publisher = yield From( 
            manager.advertise('/gazebo/' + world_name + '/' + robot_name + '/joint_cmd', 
                              'gazebo.msgs.JointCmd')) 
 
        message = pygazebo.msg.joint_cmd_pb2.JointCmd() 
        message.name = robot_name + '::' + joint_name #format should be: name_of_robot + '::name_of_joint' 
        message.force = force 
 
 
        #t_end = time.time() + duration # The time that you want the controller to stop 
        while True: #time.time() < t_end or duration == -1: 
            try: 
                yield From(publisher.publish(message)) 
                yield From(trollius.sleep(1.0)) 
            except: 
                pass 
             #Nothing    
        print("Connection closed") 
 
    wait_net_service('localhost',11345) 
 
 
    loop = trollius.new_event_loop() 
    loop.run_until_complete(joint_force_loop()) 
    raise      
 
 
def wait_net_service(server, port, timeout=None): 
    """ Wait for network service to appear  
        @param timeout: in seconds, if None or 0 wait forever 
        @return: True of False, if timeout is None may return only True or 
                 throw unhandled network exception 
    """ 
    import socket 
    import errno 
 
    s = socket.socket() 
    if timeout: 
        from time import time as now 
        # time module is needed to calc timeout shared between two exceptions 
        end = now() + timeout 
 
    while True: 
        try: 
            if timeout: 
                next_timeout = end - now() 
                if next_timeout < 0: 
                    return False 
                else: 
                    s.settimeout(next_timeout) 
            s.connect((server, port)) 
            time.sleep(1) 
        except socket.timeout, err: 
            # this exception occurs only if timeout is set 
            if timeout: 
                return False 
 
        except socket.error, err: 
            # catch timeout exception from underlying network library 
            # this one is different from socket.timeout 
            if type(err.args) != tuple or (err[0] != errno.ETIMEDOUT and err[0] != errno.ECONNREFUSED): 
                raise err 
        else: 
            s.close() 
            return True 

我认为@coroutines 应该被异步包装?我只是误解了使用这段代码吗?还是我做错了什么?顺便说一句,这是我第一次在 Python 中使用并发。

这也是我调用该函数的方式:

    counter = 0 
    for joint_def in self.all_joint_props: 
        print("each joint_def") 
        apply_joint_force(world_name, robot_name, "hingejoint" + str(counter), joint_def[2]) 
        #print("Appliing joint force") 

知道为什么它一直阻塞线程吗?我应该对此使用不同的方法吗?任何帮助将不胜感激

请您参考如下方法:

所以,答案真的很简单。在启动对象之前,您必须将要作为列表运行的多个 Trollius.Tasks 排队,并将其与 Trollius.wait() 结合使用以实现此目的。为确保线程是非阻塞的,然后使用以下 method

到目前为止,这是我的代码:

tasks = [] 
for joint_name in joint_names: 
    tasks.append(trollius.Task(joint_force_loop(world_name, robot_name, joint_name, force, duration)) 
loop = trollius.get_event_loop() 
loop.run_until_complete(trollius.wait(tasks))