Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

run ros terminal commands within a python script

I have my ros program ready, and I can control my robot using the terminal commands. Now, I am trying to write a python script to control the robot as I do with the terminal commands. For this purpose, I have been trying several methods explained by others. As expected, I begin with starting the roscore. However, I get error and cannot proceed. Here are what I have done so far:

1- As given here, I ran the following code

import subprocess 
roscore = subprocess.Popen('roscore') 
time.sleep(1)

and got this error:

>>> runfile('/opt/ros/kinetic/bin/run_roscore.py', wdir='/opt/ros/kinetic/bin')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/dist-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 699, in runfile
    execfile(filename, namespace)
  File "/usr/lib/python2.7/dist-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 81, in execfile
    builtins.execfile(filename, *where)
  File "/opt/ros/kinetic/bin/run_roscore.py", line 20, in <module>
    roscore = subprocess.Popen('roscore')
  File "/usr/lib/python2.7/subprocess.py", line 711, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1343, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

2- Trying the same code with shell=True option,

roscore = subprocess.Popen('roscore', shell=True)

gives the output:

runfile('/opt/ros/kinetic/bin/run_roscore.py', wdir='/opt/ros/kinetic/bin')
/bin/sh: 1: roscore: not found

3- I also tired other libaries: os and commands

import os
os.system('roscore')

and

import commands
a=commands.getoutput('roscore')
print a

to get the same error:

runfile('/opt/ros/kinetic/bin/run_roscore.py', wdir='/opt/ros/kinetic/bin')
sh: 1: roscore: not found

4- I can run general linux commands with no error. For example the codes below successfully lists the files:

os.system('ls -l')
subprocess.Popen('ls -l', shell=True)
a=commands.getoutput('ls -l')
print a

Here, run_roscore.py is my python file and I placed it in the same directory with roscore file.

According to my intuition, it looks like a problem with setup.bash file, but I cannot figure out what the problem is.

I am using ROS Kinetic and Ubuntu 16.04 LTS on Nvidia Jetson TX2 developer kit

When giving your answer please, keep in mind that I am not experienced with ROS and Ubuntu environments. So I appreciate if you provide the steps clearly.

Also, please note that starting the roscore is an error I encountered at the beginning of my ultimate goal. At the next steps, I will need to run other commands such as

rostopic pub servo std_msgs/UInt16 80

and

rosrun rosserial_python serial_node.py /dev/ttyACM0

So you may also provide a general recommendation covering my overall goal.