Parallel Processing in Python with Robot - python

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.

Related

Pre-inputting information in an input() function

I have a program that is executed. After that, the user has an option to load back their previous input() answers or to create a new one (just re-execute the program). The program is based on user input and so if I wanted to reload the user's previous inputs, is there a way to pre code an input with the user's previous answer? As a crude example of what my program does I just made this:
def program():
raw_input=input()
print("Would you like to reload previous program (press 1) or create new? (press 2)")
raw_input2=input()
if raw_input2==2:
program()
elif raw_input2==1:
#And here is where I would want to print another input with the saved 'raw_input' already loaded into the input box.
else:
print("Not valid")
For any confusion this is my original code:
while True:
textbox1=input(f" Line {line_number}: ")
line_number+=1
if textbox1:
commands.append(textbox1)
else: #if the line is empty finish inputting commands
break
print("\033[1m"+"*"*115+"\033[0m")
for cmd in commands:
execute_command(cmd)
line_numbers+=1
I tried creating a Python-like coding program using Python which generates new inputs (new lines) until you want to end your program by entering in nothing. This is only a snippet of my code of course. The problem I'm having is that after the user finished writing their basic program, whether you got an error because your code didn't make send or if it actually worked, I want there to be a 'cutscene' where it asks the user if they want to reload their previous program (because rewriting you program everytime there's an error is hard). I'm just asking whether I can do something like this: If my program was print("Hi"), and I wanted to reload it, I want to get an input; raw_input=input() but I want print("Hi") already inside the input().
This is not possible with the built-in input function. You will need a more fully-featured CLI library like readline or prompt-toolkit.
Some notes:
The input function always returns strings.
The while True keeps going until either 1 or 2 is entered
You can pass a string with the input-function call to specify what input is expexted.
If you put this in a loop you could re-ask the question, and you should then update the prev_answer variable each iteration.
prev_answer = 'abc'
while True:
raw_input2=input("Would you like to reload previous program (press 1) or create new? (press 2)")
if raw_input2=='2':
user_input = input('Please give your new input')
elif raw_input2=='1':
user_input = prev_answer
if raw_input2 in ('1','2'):
break
print(user_input)
Based on edit:
prev_answer = 'abc'
while True:
raw_input2=input("Would you like to reload previous program (press 1) or create new? (press 2)")
if raw_input2=='2':
user_input = input('Please give your new input')
elif raw_input2=='1':
print(prev_answer)
user_input = prev_answer + ' ' + input()
if raw_input2 in ('1','2'):
break

windows Command prompt vanishes after running a python script converted to .exe using pyinstaller

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")

Run a function between two inputs in the console

I have a Script that works well, but I would like to add an implementation to it.
In first place, I am using the Script to communicate with a couple of devices (Frequency generator and Oscilloscope) via PyVISA and get some measurements. At a certain step during the process, I have to adjust manually a Photodetector (physical device that cannot be used with PyVISA, but attached to the oscilloscope) with a knob which is very sensitive and can be damaged. I am using my own function to control the damage measuring the voltage through the oscilloscope, named PreventAPD. Mainly the function reads the voltage of the oscilloscope and if it is larger than a certain level it stops the system.
When running the script, there is a moment when a message is shown in the console to proceed to the adjustment, I want at this moment to start running the PreventAPD function and that it stops running when the adjustment is done and I push Enter in the console again. The adjustment time can take uncertian times, sometimes 1 min or maybe 3 mins.
The code below shows an example of my question.
print('Adjust manually the Gain from the APD')
input('Press Enter to continue') <---- From here
PreventAPD() <---- Function to run
PreventLD() <---- Function to run
M = int(input("Insert the value of M: "))
print(f"The value of M is {M}")
input('Press Enter to continue') <---- Until here
Does anyone have any idea?
… the script runs the functions between the two inputs in the console, but just once. … I would like it to be running in a loop that starts with an input console and stops with another input console.
You could use a KeyboardInterrupt exception to break a loop:
print('Adjust manually the Gain from the APD')
input('Press Enter to continue')
print('Press Interrupt (Ctrl-C) to enter M')
try:
while True:
PreventAPD()
PreventLD()
except KeyboardInterrupt:
pass
M = int(input("Insert the value of M: "))

Working multiple consoles in python

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

How to pause and wait for command input in a Python script

Is it possible to have a script like the following in Python?
...
Pause
->
Wait for the user to execute some commands in the terminal (e.g.
to print the value of a variable, to import a library, or whatever).
The script will keep waiting if the user does not input anything.
->
Continue execution of the remaining part of the script
Essentially the script gives the control to the Python command line interpreter temporarily, and resume after the user somehow finishes that part.
What I come up with (inspired by the answer) is something like the following:
x = 1
i_cmd = 1
while True:
s = raw_input('Input [{0:d}] '.format(i_cmd))
i_cmd += 1
n = len(s)
if n > 0 and s.lower() == 'break'[0:n]:
break
exec(s)
print 'x = ', x
print 'I am out of the loop.'
if you are using Python 2.x: raw_input()
Python 3.x: input()
Example:
# Do some stuff in script
variable = raw_input('input something!: ')
# Do stuff with variable
The best way I know to do this is to use the pdb debugger. So put
import pdb
at the top of your program, and then use
pdb.set_trace()
for your "pause".
At the (Pdb) prompt you can enter commands such as
(Pdb) print 'x = ', x
and you can also step through code, though that's not your goal here. When you are done simply type
(Pdb) c
or any subset of the word 'continue', and the code will resume execution.
A nice easy introduction to the debugger as of Nov 2015 is at Debugging in Python, but there are of course many such sources if you google 'python debugger' or 'python pdb'.
Waiting for user input to 'proceed':
The input function will indeed stop execution of the script until a user does something. Here's an example showing how execution may be manually continued after reviewing pre-determined variables of interest:
var1 = "Interesting value to see"
print("My variable of interest is {}".format(var1))
key_pressed = input('Press ENTER to continue: ')
Proceed after waiting pre-defined time:
Another case I find to be helpful is to put in a delay, so that I can read previous outputs and decide to Ctrl + C if I want the script to terminate at a nice point, but continue if I do nothing.
import time.sleep
var2 = "Some value I want to see"
print("My variable of interest is {}".format(var2))
print("Sleeping for 5 seconds")
time.sleep(5) # Delay for 5 seconds
Actual Debugger for executable Command Line:
Please see answers above on using pdb for stepping through code
Reference: Python’s time.sleep() – Pause, Stop, Wait or Sleep your Python Code
I think you are looking for something like this:
import re
# Get user's name
name = raw_input("Please enter name: ")
# While name has incorrect characters
while re.search('[^a-zA-Z\n]',name):
# Print out an error
print("illegal name - Please use only letters")
# Ask for the name again (if it's incorrect, while loop starts again)
name = raw_input("Please enter name: ")
Simply use the input() function as follows:
# Code to be run before pause
input() # Waits for user to type any character and
# press Enter or just press Enter twice
# Code to be run after pause

Categories

Resources