0

currently I am writing a robot operating system (ros) node in python. I want to create a while loop which accepts user input on the one hand but is able to continue if no user input is available.

The idea of the following snippet is, that this python-script offers always 'start' or 'stop'. Another node is listening what string gets published. The user should be able to type in 0 or 1 at runtime to toggle the flag.

Here is my python code:

def main():
    pub = rospy.Publisher('/start_stop', String, queue_size=10)
    rospy.init_node('start_stop', anonymous = True);
    rate=rospy.Rate(10)  # 10hz
    pubStr = "Start"
    while not rospy.is_shutdown():
        try:
            input = raw_input()
            if input == "0":
                pubStr = "Stop"
            elif input == "1":
                pubStr = "Start"
        except:
            rospy.sleep(0.1)
        rospy.loginfo(pubStr)
        pub.publish(pubStr)
        rate.sleep()

if __name__ == '__main__':
    main();
Jochen
  • 1,746
  • 4
  • 22
  • 48
  • 1
    So you are seeking a non-blocking input function, correct? – Dilettant Jun 14 '16 at 10:30
  • Yes, I think I am looking for way to get this done. – Jochen Jun 14 '16 at 10:42
  • Maybe look at [Python: taking input from sys.stdin, non-blocking](http://stackoverflow.com/questions/21791621/python-taking-input-from-sys-stdin-non-blocking) for ideas ... or [Python nonblocking console input](http://stackoverflow.com/questions/2408560/python-nonblocking-console-input). HTH – Dilettant Jun 14 '16 at 10:45

1 Answers1

1

In case you don't find a way to do this directly in Python, an easy solution would be to move the user input to another node:

  • The first node (let's call it "user input node") looks basically like the code you posted, but publishes directly the value of input to a topic /user_input.
  • The second node ("start/stop node") publishes the "Start"/"Stop" in a loop, depending on the flag. This flag is set by a callback listening to /user_input.

This way, the start/stop node always publishes depending on the user input, without waiting for new input, while the user can always change the flag by sending a new value via the user input node.

This solution would be easy to implement but has the downside of an additional node in your setup.

luator
  • 4,769
  • 3
  • 30
  • 51