Implement terminal command recall - python

In the command line when up and down arrow is pressed it shows the last command in the same line. I want to implement that functionality in my program. What I have done is store previous command in a list. I can iterate it from the end and print it out but I can only print out in a new line. What is that functionality called and how to implement it?

It's called "history". It is implemented in readline, and is automatically enabled for input() and raw_input() when the module is imported; only loading and saving the history needs to be handled by the implementor.

Related

How to execute another python file and then close the existing one?

I am working on a program that requires to call another python script and truncate the execution of the current file. I tried doing the same using the os.close() function. As follows:
def call_otherfile(self):
os.system("python file2.py") #Execute new script
os.close() #close Current Script
Using the above code I am able to open the second file but am unable to close the current one.I know I am silly mistake but unable to figure out what's it.
To do this you will need to spawn a subprocess directly. This can either be done with a more low-level fork and exec model, as is traditional in Unix, or with a higher-level API like subprocess.
import subprocess
import sys
def spawn_program_and_die(program, exit_code=0):
"""
Start an external program and exit the script
with the specified return code.
Takes the parameter program, which is a list
that corresponds to the argv of your command.
"""
# Start the external program
subprocess.Popen(program)
# We have started the program, and can suspend this interpreter
sys.exit(exit_code)
spawn_program_and_die(['python', 'path/to/my/script.py'])
# Or, as in OP's example
spawn_program_and_die(['python', 'file2.py'])
Also, just a note on your original code. os.close corresponds to the Unix syscall close, which tells the kernel that your program that you no longer need a file descriptor. It is not supposed to be used to exit the program.
If you don't want to define your own function, you could always just call subprocess.Popen directly like Popen(['python', 'file2.py'])
Use the subprocess module which is the suggested way to do that kind of stuff (execute new script, process), in particular look at Popen for starting a new process and to terminate the current program you can use sys.exit().
Its very simple use os.startfile and after that use exit() or sys.exit() it will work 100%
#file 1 os.startfile("file2.py") exit()

Programmatically injecting command into Python Cmd's cmdloop

Using Python Cmd2 module (inherits from Cmd) to create a MyCmd CLI for my program. In most cases, I am just using my script normally with the built-in commands. The ‘quit’ command is implemented to do some cleanup for the script and subsequently exit. The Cmd2 module waits for input via the raw_input.
In a specific case, I want to programmatically invoke ‘quit’ instead of issuing it at the command line. This is done via a separate thread where a REST API translates a ‘quit’ POST to invoke quit on the main thread of the script.
I found a couple of SO questions that want to do something similar, but not exactly like this. I tried to follow the below example, but it didn’t work:
Python StringIO - selectively place data into stdin
Then I tried something simple. Basically did the below from the thread:
sys.stdin = StringIO('quit\n')
sys.stdin.flush()
It seems that the word 'quit' was injected, but the script would not do its clean exit. However, I could go back to the command line and simply press Enter, which would trigger the cleanup and exit process. Not sure why ‘\n’ was not being interpreted as Enter.
My cmd is simply invoked in the below manner:
mycmd = MyCmd()
mycmd.cmdloop()
How can I properly inject ‘quit’ into the cmdloop of Cmd?
Have you tried the cmd.onecmd("quit") method? I think it can be used to inject commands in the interpreter.

Run same script "infinite" times

I have a script that does random calculation and prints it, but now I need these results written in a text file. I edited it and now each time I execute this script, new results are appended in a text file. However, I need as many new results as I can get into the same text file, so is there a way to make it run again and again (and stop it when I want to by keyboard interrupt)?
I could do something like:
inf_loop=0
while inf_loop==0:
#code to append to text file
But the script is rather long, thus I need to have each line within the loop indented properly.
I cannot comment so I'm gonna say my opinion here.
tab is your friend here. If you're using Python IDLE, just select all the lines and hit Tab. If you wanna outdent, try shift + tab.
If indenting is a problem for you and you really want to hack this down, you could simply restart your script like this:
#!/usr/bin/env python
import os
# your script content
args=['some_name']
os.execlp('./your_script.py',*args)
Run the script from the directory it is located in. If you need to pass arguments, simply append them to args.
If your script finishes it will restart itself again and again...
If you're adamant that you don't want to change your existing script, create a new one, then keep calling the other...
while True:
execfile('/path/to/other/script.py')
Although you should really be putting the work of the other script into a function, then repeatedly calling that instead of the script...
while True:
call_your_function()

How to open a powershell terminal with one python script?

I am working on a text based game that I run by double clicking on my top level script namely TopLevel.py.
I am looking for a way to open two terminals in this script. In the one terminal the main game will be run where damage is done and spells are used etc. In the other terminal I would like to display a list of commands that the user can type in , and I want the latter one to stay there and not close until the game is finished. I am not going to show you the whole top level script (it is too long) but this is basically what I want to achieve:
def displayCommands(hero):
list_of_commands = []
#this contains all my commands that the user can type in
def main():
hero = Hero() #make hero instance
enemy = Enemy() #make and enemy instance
a_game = TopLevel(hero,enemy) #create game engine
a_game.play() #start game
#implement code here to open another terminal
#and display user commands in there
Is there a way that I can open another terminal in this script and pass the displayCommands() function as a parameter to display its contents in the second terminal? Any help will be appreciated :)
It's possible for one Python script to spawn another that will run in parallel with it via subprocess. The spawned process can then display any text piped to it (via normal print statements or calls) in a simple tkinter-based window -- see the errorwindow module in this answer of mine for more information.
It likely doesn't matter how the original script gets started. I personally have used it both in ones that were started from a command shell as well as from other tkinter based applications -- so starting yours from powershell should be fine. The module's original author was using Linux or something similar, I believe.
You should convert your second program to .exe first,the one will display user commands. Say you saved it as usercommands.exe, after then in your main script use this to open that;
import subprocess
subprocess.Popen([r"usercommands.exe"],
creationflags=subprocess.CREATE_NEW_CONSOLE)
It'll open another console window that runs usercommands.exe when you run your main file.
Notes;
They must be in the same directory, your main file and .exe file
usercommands.exe must show the commands in an infinite loop(while True), so it's
going to display commands untill the user close it.
Edit;
Now, we have some spells and usercommands will have to use that spell variables after then show us some combinations. For doing this, we have to import your first file to usercommands script.It's going to like this;
usercommands.py
import mainfile #mainfile.py
if choose == mainfile.wizard:
print (something)
if choose == mainfile.subzero:
print (something)
The algorithm should be like this,you will convert usercommands.py to .exe then it will work as you want I guess, we can't now before you try it ;)

how to wait until user quit text editor to take data to a variable using python?

In my Python command line tool I have a flag that I used to launch a text editor, but I want the terminal to wait until user has finished and exits the application and then pass on the text entered to a variable to be used later. I am guessing this can be done using a subprocess like below, but I am getting an error.
Code
pr = subprocess.Popen(sublime, stdin=diff.stdout)
while pr:
data = pr.stdout.read()
print data
Error
AttributeError: 'NoneType' object has no attribute 'read'.
SublimeText's command-line launcher has an optional flag (IIRC it's -w) that makes it wait until the user closes the window to return.
However, you should be aware that you can't simply read from the text editor's stdout. You need to provide it with a temporary file for the user to edit, and then read the data back from that temp file once the subl command exits.

Categories