I am working on ROS and I have written a code in Python 2.7 and in the menu I am asking the user to select either option 1 or 2. After the task is accomplished, when I press Ctrl+c, instead of exiting the code, it displays the menu again, instead of exiting. Here again if I choose between 1 or 2, it keeps printing the menu again and again.
What changes in the code would be suggested in order to exit the code as soon as I press Ctrl+c instead of displaying the menu again and again?
The code and the screen shot of the problem are below:
if __name__=='__main__':
while(True):
try:
print "***********"
print "1. Continuous"
print "2. Single Step"
print "***********"
try:
choice = int(raw_input('Choose a number between 1 & 2: '))
number = choice
move_group_python_interface()
except ValueError:
print "ERROR! Choose a number between 1 and 2"
except rospy.ROSInterruptException:
break
Without looking at move_group_python_interface() it is very difficult to say.
Examining your error screen shot (in the future, include the error text in the question), you were hitting ^C as part of the flow when move_group_python_interface() was triggered.
If move_group_python_interface() entails starting a new process, then you exited that process.
Try hitting ^C as part of the menu flow. It seems to exit fine for me.
If you are curious about how to capture ^C and respond accordingly
Check this out
if __name__=='__main__':
while(True):
try:
print "***********"
print "1. Continuous"
print "2. Single Step"
print "***********"
try:
choice = int(raw_input('Choose a number between 1 & 2: '))
number = choice
move_group_python_interface()
except ValueError:
print "ERROR! Choose a number between 1 and 2"
except KeyboardInterrupt:
print "Bye bye"
break
when executed prints
bash > python infloop.py
***********
1. Continuous
2. Single Step
***********
Choose a number between 1 & 2: ^CBye bye
(Sorry but I don't got ROS)
I found the issue. The problem was with while(True):. Once I comment it out, it exits without any problem.
Related
I am using python3.7
I wrote a script which takes some inputs (e.g. a=input("enter a value")
it runs smoothly if i go to its path and run it on command prompt.
I can give input also and run .
If i give wrong input it shows an error or exception(traceback)
So i converted it to .exe using pyinstaller
when i run .exe , it asks for input as expected ,it runs and vanishes , i can't see any output.
if i give a wrong input it suddenly vanishes without showing any traceback
I read many questions regarding this on stackoverflow and google , so i added an input statement at end to make program wait before exiting,
but it doesn't works in case of wrong input or if i use sys.exit("test failed") in some cases it just vanishes ,how to resolve and keep cmd window open?
Adding script for e.g.:
import sys
x = int(input(" enter a number :"))
y = int(input(" enter a number :"))
if x>100 or y > 100 :
sys.exit("ERROR :value out of range")
z=x+y;
print(z)
input('press enter to exit')
if inputs are less than 100 and integer then script(.exe file) runs smoothly and i get message "press enter to exit"
but if input number greater than 100 or if i put a "string or float" in input , cmd window vanishes without display any traceback
whereas if i run py file from cmd then i get proper traceback for wrong input.
You could use try-except and input() function, so that when there is any error, it will wait for the user to interact.
Look at this example -
a = input('Please enter a number: ')
try:
int(a) # Converts into a integer type
except ValueError as v:
# This will run when it cannot be converted or if there is any error
print(v) # Shows the error
input() # Waits for user input before closing
For your e.g code, try this -
import sys
try:
x = int(input(" enter a number :"))
y = int(input(" enter a number :"))
except ValueError as v:
print(v)
input('Press any key to exit ')
sys.exit()
if x>100 or y > 100 :
try:
sys.exit("ERROR :value out of range")
except SystemExit as s:
print(s)
input('Press any key to exit ')
sys.exit()
z=x+y
print(z)
You will see that the command prompt does not close immediately
You're not waiting for input.
When you run a .exe that's set up to run in the Windows console, unless you've already opened the console and if your program through that using console commands, and it was set up to just run all the way through to the end, you'll just see the window pop up and then close itself unless your program is doing something that requires user input or a lot of computational time.
This is fairly common sight when programming with languages like C# that natively run as .exes; presumably, this behaviour would also be fairly common in Python. The way to fix this is to add in a line at the end of your program to ask the user for input, so that the console will wait for the user before closing.
In your case, you mention that you have added to the end of your program; the problem is that the program isn't getting to that stage because it's hitting an exception and then exiting. You'll need to handle your exceptions and add a prompt for user input to prevent this behaviour.
Use while loop so if you gave wrong input then it will return to input again so you can give any input. and for example if you want to use only integer value then input must be convert as integer or string depend on you. example below now I think you can
ask = "" #ask variable empty here because I want to use in while condition
print("YOU LOVE ME")
while ask != 'Ok Son':
ask = input("Why? : ")
print("OK THANKS DAD")
I have coded a robot that runs modules containing the commands necessary to carry out a specific process. As of now, the user inputs the desired command, my code uses an if statement to determine what command they entered, and it runs the appropriate command. However, the command must be finished before the user can input another command.
Now I would like to do the following: have the user input a command, start the command, and, while the command is running, rerun the command to get the users input.
For example, the user inputs move forward, the robot starts moving, then the user changes the command to move backward midway through the robot moving forward, and the robot resets and starts moving backward in response.
Below is the code of the while loop that runs the modules and askes for user input. Let me know if you have any ideas on how I can achieve this or if you need any clarification. I am a high schooler who is still learning how to code, so any help would be greatly appreciated.
Thanks in advance.
Best,
Christopher
#runs all the modules and gets user input
while True:
defultPosition()
command = raw_input("Enter move forward, move backward, turn or cancel: ")
defultPosition()
if command == "cancel":
break
if command == ("move forward") or (command == "move backward"):
speedInput = input("Enter the desired speed: ")
distanceInput = input("Enter the number of inches you wish the robot to move (must be a factor of 5): ")
if command == "turn":
speedInput = input("Enter the desired speed: ")
degrees = input("Enter the number of degrees for the robot to move: ")
print ("\nINPUTED COMMAND: %s \n" % command)
if command == "move forward":
#run the moveForward module
print "Initiating command\n"
moveForward(speedInput, distanceInput)
print "Finished command; restarting and waiting for another input \n"
if command == "move backward":
#run the moveBackward module
print "Initiating command\n"
moveBackward(speedInput, distanceInput)
print "Finished command; restarting and waiting for another input \n"
if command == "turn":
#runs the turn module
print "Initiating command\n"
turnCounterClockwise(speedInput, degrees)
print "Finished command; restarting and waiting for another input \n"
I have determined that using threading is the best solution to my problem. It is able to send termination signals at any point in the program and it will restart the thread with new parameters.
Let me know if anyone would like to view the code I used.
This part of my code is giving me problems with the raw_input. The thing is, the terminal does not detect any problems and the program runs, however it never asks the user for input, the program just prints what it has to print at the beginning and then exits for some odd reasons, everything inside the while is not executed. Thanks in advance.
Heres the code:
options_secondscenario = ['Whats going on out there?', 'So what now?']
def second_scenario():
print "Conversation 1"
print "Conversation 2"
print "Conversation 3"
print options_secondscenario
option = options_secondscenario[1]
while next == option:
choice_secondscenario = raw_input("> ")
if next == 'Whats going on out there?':
print "Conversation 4"
elif next == 'So what now':
third_scenario()
else:
dead()
second_scenario()
next == option is never true, because next is a built-in function and is never equal to a string. In fact, this would actually be an error in Python 3. So your while loop is never entered.
I know that it is an easy question but I can't do this. I have to do two things. One of them is a management program that will manage the program, e.g stop, pause, resume. The other thing will only show logs. So I need 2 consoles.
How can I open two consoles?
How to pass a log from management console to logging console. Example code is below:
if __name__ == '__main__':
try:
while True:
initialmyProgram()
print('Please press \'1\' key to stop program..\n')
print('Please press \'5\' key to resume program..\n')
print('Please press \'0\' key to exit program..\n')
isStart = raw_input('Please press a key that must be in above list..')
if isStart == 1:
parse.__is__process__ = False
elif isStart == 5:
parse.__is__process__ = True
elif isStart == 0 :
exit_program()
else:
continue
except Exception as ex:
logging.info('log..') #this log will write other console..
You don't really need two python consoles to accomplish this.
If you're using linux or a mac, open up a python console and a second terminal.
Then type this command in the second terminal:
tail -f path_to/filename_of_logfile
This will refresh the log file automatically.
An alternative solution if you absolutely cannot use files, is to use sockets to have to python programs communicate. Here's a link to get you started:
Python Sockets
I am creating a text-RPG taking inspiration from older text adventures where the player enters an English command; such as 'pick up sword' and the like.
I have established a simple; enter 'A' to do this and enter 'B' to do this, but I would like to expand my system for more freedom.
I need to create a system that; when the player types in a command the program picks out key words.
I assume this would be achievable via the 'in' command.
Here is my code:
print "What would you like to do??"
input_loop_sleep = str('')
choice_sleep = raw_input(str('>>>'))
loop_sleep = False
table_time = False
bed_time = False
error_time = False
while loop_sleep == False:
if str('sleep') in choice_sleep or str('bed') in choice_sleep or str('goodnight') in choice_sleep or str('Sleep') in choice_sleep or str('tired') in choice_sleep:
while bed_time == False:
print "you decide to go back to sleep"
time.sleep(1)
print "..."
time.sleep(1)
print ""
time.sleep(1)
print "darkness"
time.sleep(1)
print ""
print "you wake up..."
time.sleep(1)
print "it is now 9:15am"
time == int(9.15)
time.sleep(1)
print "You are standing in your room, slightly more refreshed."
time.sleep(1)
print "there is a table with some things on it, stairs, and a wardrobe... with the doors wide open..."
time.sleep(1)
print "that's strange... you swear that they were shut when you went to sleep..."
break
else:
bed_time == True
break
bed_loop_choice = raw_input('>>>')
elif str('bedside') in choice_sleep or str('table') in str(choice_sleep):
while table_time == False:
print "You rub your eyes and pick up some belongings from a"
print "bedside table."
time.sleep(1)
print "Map added!"
time.sleep(1)
print "100 gold added!"
time.sleep(1)
print "Leather Bag added!"
cash == int(100)
time.sleep(1)
Map == str('map of', str(province))
Inventory == [str(Map)]
container == str('leather bag')
print "your", str(container), str("contains a"), str(Map), str('and'), str(cash)
break
else:
table_time == True
break
else:
print "invalid command!"
when I run the code, no matter what I type in it always goes with the 'sleep' option.
I probably just made some simple mistake!
can you please help me with what I did wrong and how I can fix it.
To answer your question about why the sleep loop is repeated all the time:
You're controlling the loop via
while bed_time == False:
but you never set bed_time to True in your loop (only in the else clause, but that clause is only executed when the loop exits normally, not when it's exited via break, as you're now doing - therefore bed_time will never change).
Furthermore, direct comparisons to a boolean value are usually frowned upon. The idiomatic way (in most languages, not just Python) would be while not bedtime:.
You should probably read some beginners' programming books and/or the Python tutorial before embarking on such a big project. There are several issues in your code that convey the impression that you really need to get a grasp on some basic programming principles and Python idioms.
For example,
int(9.15)
is not a good way to store a time - the result will be 9.
You're then using time == int(9.15), which means "compare the module time to the integer 9". I guess you meant time = int(9.15) which is already bad for the reasons stated above, but there would be even another problem: You would be overwriting the module name time, which will cause the subsequent time.sleep(1) command to fail with an AttributeError.
There's no need for most str() calls in your code because you're using it on objects that already are strings. Where you're not, it's incorrect: str('map of', str(province)) will raise TypeError (str takes only one argument).
You're using uppercase variable names for objects that aren't class instances.
Etc., etc...
I think this should be sufficient to sort out the problem
In [1]: str('bed') in "bedside"
Out[1]: True
So when you write bedside it gets inside the sleep option if condition and hence you are getting wrong answer .
You should write :
if str('bed') == choice_sleep or *other conditions* :
then got inside the sleep option
P.S: I am assuming you have imported the time module .
P.P.S: I checked the code with entering table it is working fine .