Python command to jump into interactive mode from a script - python

I have a python script that runs and accepts user input to make decisions. Based on the input I would like to give the user control of the python repl. Here is an example:
def func():
# hand over control to the user
breakpoint()
while True:
print('What would you like to do?\nq: quit\ni: interact')
i = input()
if i=='q':
break
elif i=='i':
func()
else:
print(f'invalid command: {i}')
Calling this code snippet with for example ipython3, the user is prompted for input. When the user presses i, func() is called, at which point I would like the user to be able to type python commands such as print(i).
My current best solution is to then set a breakpoint, the user may then need to type r to get to the right frame and then must then type interact. This is nearly acceptable, but I would like my user to not need to know that I'm using a debugger to give them interactive control, rather I would like them to be given an ipython prompt directly.
I looked at this post from 10 years ago: Jump into a Python Interactive Session mid-program? rz.'s comment looks interesting, but it looks like too much has changed for me to use his answer as is, plus there may be newer ways of doing things.

Related

IDLE does not Run Module

New here and very novice in Python. I have a question about Python.
At my workplace, I have some trainings with PL/SQL, where our first task was create RPN calculator. Because I'm not that good in PL/SQL and syntax of that language is strange in my opinion, I made it in Python.
Everything worked smoothly, until a time when I was asked to create function to check if string of values are RPN. Just before that, I made simple program to check if entered values match with those in dictionary, but I stopped to Run.
AcceptedChars = ["0","1","2","3","4","5","6","7","8","9","+","-","/","*"," "]
def checking_for_rpn():
checking = str(input("Enter values for check: "))
for AcceptedCharsCheck in checking:
if not(AcceptedCharsCheck in AcceptedChars):
print("False")
return False
print("Ok")
return True
Then, I added some crazy codes from web for checking RPN and that's fricked my code.
Now, I canot run it by Run Module. Shell displays standard view when it's ready.

Why does a PyInstaller executable terminate when the built-in quit function is mentioned (not called)?

In the below code, the list of dictionaries named options contains mention of the quit built-in function. The function is not called until it passes a check against user input. Its name is just stored in that list for when it's needed later.
def my_function():
input("my_function successfully executed, input anything to end program> ")
def choose_from_menu():
options = [
{"description":". Execute my_function.",
"method":my_function},
{"description":". Terminate program.",
"method":quit}
]
for i in options:
print(str(options.index(i) + 1) + i["description"])
chosen = input("Choose an option. > ")
for i in options:
if chosen == str(options.index(i) + 1):
# here it gets called
i["method"]()
choose_from_menu()
Run with the Python interpreter, the script lets the user choose from the printed list, and the correlating method gets picked from options and then called.
But when this script is turned into an executable with PyInstaller (on my machine, on Windows) and run, it seems to terminate the moment it sees mention of the quit function inside the options list, therefore never reaching the input prompt in the first place. (Notably, it did this with quit, but not with my_function.)
Why?
I tried defining my own method that contains a quit call, and storing that name in the dictionary instead. It does bypass this situation. However, doing that doesn't enlighten me as to the reason for this contrast between interpreter and compiler.
When the executable is run with PowerShell's Start-Process commandlet, no error is displayed.

Is there a Python library for handling and validating user input?

I have a project that involves asking for (for now, command-line) feedback from the user every so often while its main method runs.
So far I have been using input('{my_prompt}') to obtain this input from my user, but I have to quite annoyingly handle user input every time I invoke input(). This makes my code balloon to > 5 lines of code per user input line, which feels quite excessive. Some of my user input handling includes the below.
if input.lower() not in ['y', 'n']:
raise ValueError('Not valid input! Please enter either "y" or "n"')
if input.lower() == 'y':
input = True
else:
input = False
The above could be handled in 1 line of code if the user were passing command line arguments in and I could use argparse, but unfortunately the sheer volume of prompts prevents command line arguments from being a viable option.
I am familiar with the libraries cmd and click, but as far as I can tell, they both lack the functionality that I would like from argparse, which is namely to validate the user input.
In summary, I'm looking for a user input library that validates input and can return bool values without me having to implement the conversion every time.
If all you need is to check "yes/no" prompts, click supports it natively with click.confirm:
if click.confirm("Do you want to do this thing?"):
# ... do something here ....
There are a variety of other input-handling functions part of click, which are documented in the User Input Prompts section of the documentation.

How to create a command in python that shows all available commands? like help in terminal

I am making a program witch is basically a terminal interface to a couple of math libraries that i made for school. the flow is an infinite loop in python terminal that gives you the option to call a function in the library, add values and get an answer.
The thing is that i would like to make the code less shaky buy being able to call a help input and for that i would like to make a list of all available commands.
Or even better show the different categories and make it possible to write sub helps like for example
>>> help
algebra
finance
geometry
>>>help.finance
stockmarket
personal finance
>>>help.finance.stockmarket
what: price to earnings. command: "p2e" values: stockpice, eps
note: this is just some sudo scenario i just created but something like that would work.
For now i have created if statements, but when porting in all my different libraries and categories is the the code quickly becomes repetitive.
i also now have it that if you type "help" you get every single command just out of the blue.
print("Welcome to the stockmath project ")
print("if you want to run a command just type it in below")
print("if you dont know any commands, type help")
print("_______________________________________________")
command = input()
while True:
if command == ("stm.test"):
stockmath.test()
elif command == ("help") and counter == 0:
print ("p2e, price to earnings,command = stm.p2e,"
"values: price per share, earnings per share")
elif command == ("quit"):
break
I would just again remind you that i have not built this part yet.
Use the python module cmd.
Here is a very basic example
import cmd
class SimpleCmd(cmd.Cmd):
intro = 'Welcome to this simple command prompt'
prompt = ">>"
def do_left(self,arg):
"""Go Left"""
print("Go Left")
def do_right(self,arg):
"""Go Right"""
print("Go Right")
def do_quit(self,arg):
"""Exit command prompt"""
return True
if __name__ == '__main__':
SimpleCmd().cmdloop()
The output of the program will look something like this
Welcome to this simple command prompt
>>help
Documented commands (type help <topic>):
========================================
help left right
>>help left
Go Left
The cmd module takes care of the infinite loop for you and will do a lot of the complex stuff like parsing the help documentation and providing a command history using the and arrow keys.

Present blank screen, wait for key press -- how?

'lo,
I am currently trying to code a simple routine for an experiment we are planning to run. The experiment starts by entering a subject number and creating a bunch of files. I got that part working. Next, we want the screen to go blank and display a message. Something like 'Please fill in questionnaire 1 and press [ENTER] when you are done.'
My question is, how do you recommend I present a blank screen with a message like that that waits for a certain key to be pressed?
I have quite some programming experience but haven't worked with Python before so any hints are greatly appreciated. Thanks a lot in advance for your time!
~~~~~~~~~~~~~~~~~~
Some extra info that might be relevant: We are running this on Windows XP (Service Pack 2) computers. The whole point of this is that the participant does not have access to the desktop or anything on the computer basically. We want the experiment to start and display a bunch of instructions on the screen that the subject has to follow without them being able to abort etc. Hope this makes sense.
If you're in python 2, use raw_input().
If you're using python 3, use input().
You can prompt the user for information and store the result as a string.
in python 2.x
response = raw_input("What would you like to do next?")
in python 3.x
response = input("What would you like to do next?")
On windows, you can use functions in the msvcrt module. For example, kbhit() waits until the user presses a key.
To print the blank screen before putting the prompt, I used the following
import os
import sys
VALIDINPUT = '0'
while VALIDINPUT == '0':
p = os.popen('clear')
for line1 in p.readlines():
print line1
<put the logic for reading user input here>
<put the logic to check for valid user input here and if the user input is valid, then
assign 1 to VALIDINPUT>
This will show a blank screen and the prompt until the user provides a valid input.
Hope this helps. I used this on Linux.
raw_input('Please fill in questionnaire 1 and press [ENTER] when you are done.') will wait for someone to hit [enter].
Clearing the screen may be OS/environment dependent, I am not sure.

Categories