CMD auto-completion not working correctly - python

(Python 3.3.4)
I am currently using the cmd module to build an application, but for some reason I just can't get the completion to work correctly. Whenever I hit tab it just indents my input string!!
So, if I have something like this:
(MyShell)>> ta«cursor here»
I hit «tab» and get this:
(MyShell)>> ta «cursor here»
I have tried in IDLE, the Windows Power Shell and in the Python interpreter itself, I guess...
Neither the completion of commands nor the completion of arguments work!!
The code is this:
class MyShell(cmd.Cmd):
def __init__(self):
cmd.Cmd.__init__(self)
self.intro = "Welcome to MyShell test.\nPowered by Rodrigo Serrão"
self.prompt = "(MyShell)>>"
def do_talk(self, text):
print("Hello")
stuff = ["blabla", "bananas!", "noodles"]
def complete_talk(self, text, line, s, e):
if text:
return [i for i in stuff if i.startswith(text)]
else:
return stuff
MyShell().cmdloop()
I have read some questions about this, including this one:
Python Cmd Tab Completion Problems
And it may have to do with that readline thing. I tried to import it, but apparently I don't have it.

if it is a problem of your check this approach.
Go to run and type regedit.
Go to LOCAL_MACHINE\SOFTWARE\Microsoft\Command Processor.
And change the PathCompletionChar value to 9. Usually it is 40. That means your current auto completion key is not the TAB key. After you assign the value 9 close the window and restart the CMD.
Now this would be fixed. Auto completion of paths would be working fine by the TAB key.

So I'm writing a interactive shell app on Python too, to get auto completion working, install pyreadline, the readline module is Unix specific.
If you don't know how install just execute the following line:
pip install pyreadline

Related

Prevent "runfile(...)" expression in Spyder console

I'm just getting started with Python and trying to get some easy code-examples to compile. I am using the 'Spyder' Editor and everytime I run code it shows 'runfile(...)' before the actual compiled code in the console.
Is there a way to prevent this behaviour?
Try including this instead immediately prior to your code. The terminal will now return a clean code only response:
cls = lambda: print("\033[2J\033[;H", end='')
cls()
you are trying to run the code, instead go to settings, keyboard shortcuts, and look for "run selection" it will have a shortcut assigned to it
Now select all the code and use the shortcut
it will only give you in and out

Is there an interpreter for Python similar to Pry for Ruby? [duplicate]

Is there a way to programmatically force a Python script to drop into a REPL at an arbitrary point in its execution, even if the script was launched from the command line?
I'm writing a quick and dirty plotting program, which I want to read data from stdin or a file, plot it, and then drop into the REPL to allow for the plot to be customized.
I frequently use this:
def interact():
import code
code.InteractiveConsole(locals=globals()).interact()
You could try using the interactive option for python:
python -i program.py
This will execute the code in program.py, then go to the REPL. Anything you define or import in the top level of program.py will be available.
Here's how you should do it (IPython > v0.11):
import IPython
IPython.embed()
For IPython <= v0.11:
from IPython.Shell import IPShellEmbed
ipshell = IPShellEmbed()
ipshell() # this call anywhere in your program will start IPython
You should use IPython, the Cadillac of Python REPLs. See http://ipython.org/ipython-doc/stable/interactive/reference.html#embedding-ipython
From the documentation:
It can also be useful in scientific
computing situations where it is
common to need to do some automatic,
computationally intensive part and
then stop to look at data, plots, etc.
Opening an IPython instance will give
you full access to your data and
functions, and you can resume program
execution once you are done with the
interactive part (perhaps to stop
again later, as many times as needed).
You can launch the debugger:
import pdb;pdb.set_trace()
Not sure what you want the REPL for, but the debugger is very similar.
To get use of iPython and functionality of debugger you should use ipdb,
You can use it in the same way as pdb, with the addition of :
import ipdb
ipdb.set_trace()
I just did this in one of my own scripts (it runs inside an automation framework that is a huge PITA to instrument):
x = 0 # exit loop counter
while x == 0:
user_input = raw_input("Please enter a command, or press q to quit: ")
if user_input[0] == "q":
x = 1
else:
try:
print eval(user_input)
except:
print "I can't do that, Dave."
continue
Just place this wherever you want a breakpoint, and you can check the state using the same syntax as the python interpreter (although it doesn't seem to let you do module imports).
It's not very elegant, but it doesn't require any other setup.
Great answers above, but if you would like this functionality in your IDE. Using Visual Studio Code (v1.5.*) with Python Setup:
Highlight the lines you would like to run and
right click and select Run Selection/Line in Interactive Window from the drop down.
Press shift + enter on your keyboard.
Right click on the Python file you want to execute in the file explorer and select Run Current File in Interactive Window
This will launch an interactive session, with linting, code completion and syntax highlighting:
Enter the code you would like to evaluate, and hit shift + enter on your keyboard to execute.
Enjoy Python!

Detect where Python code is running (e.g., in Spyder interpreter vs. IDLE vs. cmd)

Is there a way in Python to detect, within a process, where that process is being executed? I have some code that includes the getpass.getpass() function, which is broken in Spyder, and it's annoying to go back and forth between the command line and the IDE all the time. It would be useful if I could add code like:
if not being run from Spyder:
use getpass
else:
use alternative
Here is the solution I ended up using. After reading Markus's answer, I noticed that Spyder adds half a dozen or so environment variables to os.environ with names like SPYDER_ENCODING, SPYDER_SHELL_ID, etc. Detecting the presence of any of these seems relatively unambiguous, compared to detecting the absence of a variable with as generic a name as 'PYTHONSTARTUP'. The code is simple, and works independently of Spyder's startup script (as far as I can tell):
if any('SPYDER' in name for name in os.environ)
# use alternative
else:
# use getpass
Since the string is at the beginning of each environment variable name, you could also use str.startswith, but it's less flexible, and a little bit slower (I was curious):
>>> import timeit
>>> s = timeit.Timer("[name.startswith('SPYDER') for name in os.environ]", "import os")
>>> i = timeit.Timer("['SPYDER' in name for name in os.environ]", "import os")
>>> s.timeit()
16.18333065883474
>>> i.timeit()
6.156869294143846
The sys.executable method may or may not be useful depending on your installation. I have a couple WinPython installations and a separate Python 2.7 installation, so I was able to check the condition sys.executable.find('WinPy') == -1 to detect a folder name in the path of the executable Spyder uses. Since the warning that shows in IDLE when you try to use getpass is less "loud" than it could be, in my opinion, I ended up also checking the condition sys.executable.find('pythonw.exe') == -1 to make it slightly louder. Using sys.executable only, that method looks like:
if sys.executable.find('pythonw.exe') == sys.executable.find('WinPy') == -1:
# use getpass
else:
# use alternative
But since I want this to work on other machines, and it's much more likely that another user would modify their WinPython installation folder name than that they would rename their IDLE executable, my final code uses sys.executable to detect IDLE and os.environ to detect Spyder, providing a "louder" warning in either case and keeping the code from breaking in the latter.
if any('SPYDER' in name for name in os.environ) \
or 'pythonw.exe' in sys.executable:
password = raw_input('WARNING: PASSWORD WILL BE SHOWN ON SCREEN\n\n' * 3
+ 'Please enter your password: ')
else:
password = getpass.getpass("Please enter your password: ")
By default, Spyder uses a startup scrip, see Preferences -> Console -> Adanced setting. This option is usually set to the scientific_startup.py file that loads pylab et al.
The easiest solution is to just add a global variable to the file and then use that in your if statement, e.g. add this line at the end of scientific_startup.py:
SPYDER_IDE_ACTIVE = True
In your script:
if not 'SPYDER_IDE_ACTIVE' in globals():
use getpass
else:
use alternative
This will work without throwing an error. You can also use exceptions if you like that more.
A second solution would be (if you cannot modify that file for some reason) to just check if the environment variable PYTHONSTARTUP is set. On my machine (using the Anaconda Python stack), it is not set for a regular Python shell. You could do
import os
if not 'PYTHONSTARTUP' in os.environ:
use getpass
else:
use alternative
Spyder provides the option of executing the current editor script in a native system terminal. This would produce identical behavior as if you were running from the command line. To set this up, open the Run Settings dialog by hitting F6. Then select the radio button "Execute in an external System terminal". Now run the script as usual by hitting F5. You should be able to use getpass in the normal fashion with this approach.
You could add env variable when running in Spyder and check it in code.

How to drop into REPL (Read, Eval, Print, Loop) from Python code

Is there a way to programmatically force a Python script to drop into a REPL at an arbitrary point in its execution, even if the script was launched from the command line?
I'm writing a quick and dirty plotting program, which I want to read data from stdin or a file, plot it, and then drop into the REPL to allow for the plot to be customized.
I frequently use this:
def interact():
import code
code.InteractiveConsole(locals=globals()).interact()
You could try using the interactive option for python:
python -i program.py
This will execute the code in program.py, then go to the REPL. Anything you define or import in the top level of program.py will be available.
Here's how you should do it (IPython > v0.11):
import IPython
IPython.embed()
For IPython <= v0.11:
from IPython.Shell import IPShellEmbed
ipshell = IPShellEmbed()
ipshell() # this call anywhere in your program will start IPython
You should use IPython, the Cadillac of Python REPLs. See http://ipython.org/ipython-doc/stable/interactive/reference.html#embedding-ipython
From the documentation:
It can also be useful in scientific
computing situations where it is
common to need to do some automatic,
computationally intensive part and
then stop to look at data, plots, etc.
Opening an IPython instance will give
you full access to your data and
functions, and you can resume program
execution once you are done with the
interactive part (perhaps to stop
again later, as many times as needed).
You can launch the debugger:
import pdb;pdb.set_trace()
Not sure what you want the REPL for, but the debugger is very similar.
To get use of iPython and functionality of debugger you should use ipdb,
You can use it in the same way as pdb, with the addition of :
import ipdb
ipdb.set_trace()
I just did this in one of my own scripts (it runs inside an automation framework that is a huge PITA to instrument):
x = 0 # exit loop counter
while x == 0:
user_input = raw_input("Please enter a command, or press q to quit: ")
if user_input[0] == "q":
x = 1
else:
try:
print eval(user_input)
except:
print "I can't do that, Dave."
continue
Just place this wherever you want a breakpoint, and you can check the state using the same syntax as the python interpreter (although it doesn't seem to let you do module imports).
It's not very elegant, but it doesn't require any other setup.
Great answers above, but if you would like this functionality in your IDE. Using Visual Studio Code (v1.5.*) with Python Setup:
Highlight the lines you would like to run and
right click and select Run Selection/Line in Interactive Window from the drop down.
Press shift + enter on your keyboard.
Right click on the Python file you want to execute in the file explorer and select Run Current File in Interactive Window
This will launch an interactive session, with linting, code completion and syntax highlighting:
Enter the code you would like to evaluate, and hit shift + enter on your keyboard to execute.
Enjoy Python!

Any way to clear python's IDLE window?

I know there's a similar topic about python console, but I do not know if they are the same. I tried system("clear") and it didn't work here.
How do I clear python's IDLE window?
The "cls" and "clear" are commands which will clear a terminal (ie a DOS prompt, or terminal window). From your screenshot, you are using the shell within IDLE, which won't be affected by such things. Unfortunately, I don't think there is a way to clear the screen in IDLE. The best you could do is to scroll the screen down lots of lines, eg:
print ("\n" * 100)
Though you could put this in a function:
def cls(): print ("\n" * 100)
And then call it when needed as cls()
os.system('clear') works on linux. If you are running windows try os.system('CLS') instead.
You need to import os first like this:
import os
Most of the answers, here do clearing the DOS prompt screen, with clearing commands, which is not the question. Other answers here, were printing blank lines to show a clearing effect of the screen.
The simplest answer of this question is
It is not possible to clear python IDLE shell without some external module integration. If you really want to get a blank pure fresh shell just close the previous shell and run it again
ctrl + L clears the screen on Ubuntu Linux.
An extension for clearing the shell can be found in Issue6143 as a "feature request". This extension is included with IdleX.
>>> import os
>>>def cls():
... os.system("clear")
...
>>>cls()
That does is perfectly. No '0' printed either.
There does not appear to be a way to clear the IDLE 'shell' buffer.
The way to execute commands in Python 2.4+ is to use the subprocess module. You can use it in the same way that you use os.system.
import subprocess
subprocess.call("clear") # linux/mac
subprocess.call("cls", shell=True) # windows
If you're executing this in the python console, you'll need to do something to hide the return value (for either os.system or subprocess.call), like assigning it to a variable:
cls = subprocess.call("cls", shell=True)
I like to use:
import os
clear = lambda : os.system('cls') # or clear for Linux
clear()
File -> New Window
In the new window**
Run -> Python Shell
The problem with this method is that it will clear all the things you defined, such as variables.
Alternatively, you should just use command prompt.
open up command prompt
type "cd c:\python27"
type "python example.py" , you have to edit this using IDLE when it's not in interactive mode. If you're in python shell, file -> new window.
Note that the example.py needs to be in the same directory as C:\python27, or whatever directory you have python installed.
Then from here, you just press the UP arrow key on your keyboard. You just edit example.py, use CTRL + S, then go back to command prompt, press the UP arrow key, hit enter.
If the command prompt gets too crowded, just type "clr"
The "clr" command only works with command prompt, it will not work with IDLE.
"command + L" for MAC OS X.
"control + L" for Ubuntu
Clears the last line on the interactive session
It seems like there is no direct way for clearing the IDLE console.
One way I do it is use of exit() as the last command in my python script (.py). When I run the script, it always opens up a new console and prompt before exiting.
Upside : Console is launched fresh each time the script is executed.
Downside : Console is launched fresh each time the script is executed.
As mark.ribau said, it seems that there is no way to clear the Text widget in idle. One should edit the EditorWindow.py module and add a method and a menu item in the EditorWindow class that does something like:
self.text.tag_remove("sel", "1.0", "end")
self.text.delete("1.0", "end")
and perhaps some more tag management of which I'm unaware of.
None of these solutions worked for me on Windows 7 and within IDLE. Wound up using PowerShell, running Python within it and exiting to call "cls" in PowerShell to clear the window.
CONS: Assumes Python is already in the PATH variable. Also, this does clear your Python variables (though so does restarting the shell).
PROS: Retains any window customization you've made (color, font-size).
It seems it is impossible to do it without any external library.
An alternative way if you are using windows and don't want to open and close the shell everytime you want to clear it is by using windows command prompt.
Type python and hit enter to turn windows command prompt to python idle (make sure python is installed).
Type quit() and hit enter to turn it back to windows command prompt.
Type cls and hit enter to clear the command prompt/ windows shell.
The best way to do it on windows is using the command prompt 'cmd' and access python directory the command prompt could be found on the start menu >run>cmd
C:\>cd Python27
C:\Python27>python.exe
Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>>import os
>>>os.system('cls') #This will clear the screen and return the value 0
You can make an AutoHotKey script.
To set ctrl-r to a hotkey to clear the shell:
^r::SendInput print '\n' * 50 {Enter}
Just install AutoHotKey, put the above in a file called idle_clear.ahk, run the file, and your hotkey is active.
I would recommend you to use Thonny IDE for Python. It's shell has "Clear Shell" option and you can also track variables created in a separate list. It's debugging is very good even comparing with modern IDEs. You can also write code in python file along with access to shell at the same place.
And its lightweight!
use this
for num in range(1,100):
print("\n")
Turtle can clear the screen.
#=====================================
import turtle
wn = turtle.Screen()
wn.title("Clear the Screen")
t = turtle.Turtle()
t.color('red', 'yellow')
t.speed(0)
#=====================================
def star(x, y, length, angle):
t.penup()
t.goto(x, y)
t.pendown()
t.begin_fill()
while True:
t.forward(length)
t.left(angle)
if t.heading() == 0: #===============
break
t.end_fill()
#=====================================
# ( x, y, length, angle)
star(-360, 0, 150, 45)
t.clear()
#=====================================
This answer is for IDLE, not for the command prompt and was tested with Python 3.10.6.
If you press Ctrl+Z while the code is running (before it finishes), the previous output will be erased. If you wish to automate this, there's the pynput package.
pip install pynput
Here's a sample code (macros are unsafe, use it at your own risk):
# License: MIT-0
import time
import pynput
class _Eraser:
keyboard = pynput.keyboard.Controller()
ctrl = pynput.keyboard.Key.ctrl
is_initialized = False
#classmethod
def erase(cls, n):
if not cls.is_initialized:
cls.is_initialized = True
n += 1
for _ in range(n):
with cls.keyboard.pressed(cls.ctrl):
cls.keyboard.press('z')
cls.keyboard.release('z')
time.sleep(0.1)
def erase(n=1):
_Eraser.erase(n)
print('test1\n', end='')
print('test2\n', end='')
erase() # Erase 'test2\n'
print('test3')
print('test4')
erase() # Erase '\n'
print('test5')
print('test6')
erase(2) # Erase '\n' and then 'test6'
print('test7')
The output is:
test1
test3
test4test5
test7
This works for me in Windows:
print chr(12)
There is no need to write your own function to do this! Python has a built in clear function.
Type the following in the command prompt:
shell.clear()
If using IPython for Windows, it's
cls()

Categories

Resources