ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question
2

How can I run a node from Code?

asked 2018-11-03 19:01:29 -0500

Ivan_Sanchez gravatar image

Hi all,

I'm trying to start a node from other by code using Python but I don't know how. I use Ros kinetic.

Thanks!!

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted
3

answered 2018-11-04 05:05:27 -0500

This is possible, but I'm going to ask why you want to do this? It's quite rare for this to be necessary. Can you use a launch file to achieve the same thing, if so then I'd highly recommend you to use that option.

Any operating system command can be executed from python using the os.system("your system command") function. So you can use this to start a node the same way that you do manually from the command line:

os.system("rosrun <package_name> <node_name> <arguments. . .>")

Importantly though this command will block until the node has completed and shut down which is probably not what you want to happen. I'm guessing you want to start a node up, and then continue with the rest of your python code while this new node is also running.

To start a node in the background you'll need to use os.spawnv() to start the node and store it's process id so that your python code can kill this sub-process before it closes:

node_pid = os.spawnv(P_NOWAIT, "rosrun", ["<package_name>", "node_name>", "<arguments. . .>"])

# Some python code to execute while the new node is running

so.kill(node_pid, signal.SIGINT)

There is a danger that if your python node crashes then the node you started in the background will keep running and will still need to be killed manually. So I'd just emphasise if you can use launch files instead then use them and only manage the processes like this yourself if you can't possibly avoid it.

Hope this helps.

edit flag offensive delete link more

Comments

Any idea how to do this in c++? Icouldnt find a solution to the non_blocking version. Help would be appreciated.

Dragonslayer gravatar image Dragonslayer  ( 2020-12-05 11:24:31 -0500 )edit
0

answered 2018-11-05 13:45:18 -0500

The roslaunch API is in python and you can wrap it yourself to call from code natively. https://docs.ros.org/api/roslaunch/ht...

edit flag offensive delete link more

Comments

Would be helpful to have a code snippet of how to solve the problem .. Docs are great but in that format it's not very user friendly

pring gravatar image pring  ( 2020-05-24 19:21:20 -0500 )edit

Question Tools

2 followers

Stats

Asked: 2018-11-03 19:01:29 -0500

Seen: 1,654 times

Last updated: Nov 05 '18