I've been trying to write a little screenshot script for arch. It works, but the problem is when I try to assign it a keybinding in my i3-config it does nothing.
First I tried writing it fully in bash which worked fine but I stumbled onto the same problem with it not executing.
So I have redirected the output to a log-file to check it out and it welcomes me with this:
import: unable to grab mouse '': Datei oder Verzeichnis nicht gefunden # error/xwindow.c/XSelectWindow/9306.
import: unable to read X window image '': Erfolg # error/xwindow.c/XImportImage/4942.
import: unable to read X window image '': Erfolg # error/xwindow.c/XImportImage/5049.
import: `/home/lukas/Screenshot/20190419/scoot7.png' # error/import.c/ImportImageCommand/1288.
Translation first line: Couldn't find file or directory # error[...]
Translation Erfolg: success
I've tried googling it, which didn't lead me to anything really and I didn't really find any path resembling error/xwindow.c and so on.
Here is my code:
#!/usr/bin/env python
import os, os.path
import datetime
import sys
d = datetime.datetime.today()
directory="/home/lukas/Screenshot/%s"%d.strftime('%Y%m%d')
if not os.path.exists(directory):
os.mkdir(directory)
fileCount = 1
for file in os.listdir(directory):
if file.endswith('.png'):
fileCount+=1
filename = "%s/scr%d.png"%(directory,fileCount)
os.system("import %s"%filename)
and here is my entry to my i3 config:
bindsym $mod+Shift+F12 exec --no-startup-id scoot > /tmp/log.out 2>&1
The expected outcome of this is that when I press mod+shift+f12 it should transform my mouse-pointer to a "crosshair" so I can select something and takes a screenshot of that.
The actual result is that if I run it normaly it works, but if I try to use the Keyboard-Shortcut it just does nothing but output to my logfile.
I am pretty much a newbie to programming and linux, and I have no idea why it cannot find my mouse and I wanted to know if I can explicitly tell the program to use it or if there is another way to do this.
Thanks alot.
Hugenotte
I wrote a bash script a little while ago to do exactly what you are trying to do, using the very common utility ImageMagick that you can find here on Arch.
Here it is in case you are open to this alternative:
#!/bin/bash
# take screenshot using import from imagemagick
# allows to select the area by dragging across a rectangle
# or to select entire window by clicking inside it
set -e
# the date and time will be used as the file name
time=$(date +"%F_%H:%M:%S")
# naming the urxvt window "screenshot" so that the i3 "no_focus" option gets applied to it
urxvt -title "screenshot" -e bash -c "import $HOME/Screenshot/$time.png"
I then use it in i3 with:
no_focus [title="screenshot"]
bindsym $mod+Shift+F12 layout tabbed; exec --no-startup-id bash my_script.sh
Of course, you may want to change the date format to what you had in python. I like having the time in case I take several screenshots in a row. And you have to replace urxvt with the name of your terminal emulator and you might have to adapt the -title flag if your terminal emulator doesn't give windows a name in this way.
Note that naming the window is important: it took me a little while to figure out how to go around what happens without naming the window and using the no_focus on that window in i3:
The focus would jump to the screen capture window and thus out of the window of which I wanted to take a screenshot. It might be possible that the issue you are facing with your bash and python scripts may be related to this. You have to force i3 to keep your mouse on the old window and not jump to the screen capture window triggered by the script (by default, i3 will focus on a newly created window).
I have some code that runs perfectly fine when I run it in the python module (Python 3.3). However, when I make it an executable and try to run it in my Mac terminal nothing prints out.
The beginning of the code:
#!/usr/bin/python
import sys
marker = 1
prevchar = 'z'
prevstring = ""
#print("At place 1")
for line in sys.stdin:
#print("At place 2")
sys.stdout.write("% ")
for c in line:
#print("Starting loop")
In the terminal, when I take the comment sign off of "print("At place 1")", it prints. However, the same does not work for "print("At place 2")". What's wrong?
EDIT: I am putting data into stdin by just typing it into terminal. Maybe reading through a file would be better, though?
How do you run? You need to pipe something in you case.
cat test | python sys_test_module.py
At place 1
At place 2
At place 2
You might find this helpful http://en.wikibooks.org/wiki/Python_Programming/Input_and_output
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!
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!
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()