Python not printing in Mac terminal - python

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

Related

Hide terminal when running Python

I use Linux. I want to hide the terminal, that is, that the command is executed in Python but invisible.
Try with two method that do not work on me (maybe I do not do it well), but I want to know if there are others. What I tried was .pyw and nohup
A quick example of the code to test is:
import time
import os
x = 1
While x == 1:
os.system(f"mpg321 /beep.mp3")
time.sleep(20)

How to clear screen/terminal in python [duplicate]

This question already has answers here:
How to clear the interpreter console?
(31 answers)
Closed 4 years ago.
Does any standard "comes with batteries" method exist to clear the terminal screen from a Python script, or do I have to go curses (the libraries, not the words)?
A simple and cross-platform solution would be to use either the cls command on Windows, or clear on Unix systems. Used with os.system, this makes a nice one-liner:
import os
os.system('cls' if os.name == 'nt' else 'clear')
What about escape sequences?
print(chr(27) + "[2J")
Why hasn't anyone talked about just simply doing Ctrl+L in Windows or Cmd+L in Mac.
Surely the simplest way of clearing screen.
As for me, the most elegant variant:
import os
os.system('cls||clear')
For Windows, Mac and Linux, you can use the following code:
import subprocess, platform
if platform.system()=="Windows":
if platform.release() in {"10", "11"}:
subprocess.run("", shell=True) #Needed to fix a bug regarding Windows 10; not sure about Windows 11
print("\033c", end="")
else:
subprocess.run(["cls"])
else: #Linux and Mac
print("\033c", end="")
jamesnotjim tested print("\033c", end="") for Mac, and I tested it on Linux and Windows (it doesn't work for Windows, hence the other code that calls cls). I don't remember who it was I first saw use print("\033c") and/or the printf version: subprocess.run("printf '\033c'", shell=True).
rolika pointed out that end="" will prevent it from printing a new line afterward.
Note that newer versions of Ubuntu will clear the screen just fine (not just scroll down so it seems cleared) with clear, unlike the older versions.
Note that resetting the terminal with ESC c ("\033c") will make the cursor underlined and blinking. If you don't want that, you can use these codes to change it to another style (tested on GNOME Terminal 3.44.0 using VTE 0.68.0 +BIDI +GNUTLS +ICU +SYSTEMD):
underscore blinking: "\033[0 q"
block blinking: "\033[1 q"
block: "\033[2 q"
underscore blinking: "\033[3 q"
underscore: "\033[4 q"
thin bar blinking: "\033[5 q"
thin bar: "\033[6 q" (numbers above 6 seem to do this, too)
Also note that you can do any of these things to clear the screen on Linux:
print("\033c", end=""):
print("\u001bc", end="")
print("\U0000001bc", end="")
print("\x1bc", end="")
subprocess.run(["clear"]) #This doesn't reset the whole terminal
subprocess.run('echo -ne "\033c"', shell=True)
subprocess.run('echo -ne "\ec"', shell=True)
subprocess.run('echo -ne "\u001bc"', shell=True)
subprocess.run('echo -ne "\U0000001bc"', shell=True)
subprocess.run('echo -ne "\x1bc"', shell=True)
subprocess.run("printf '\033c'", shell=True)
subprocess.run("printf '\ec'", shell=True)
subprocess.run("printf '\u001bc'", shell=True)
subprocess.run("printf '\U0000001bc'", shell=True)
subprocess.run("printf '\x1bc'", shell=True)
I believe the following code is supposed to clear the content that you have to scroll up to see (but it's difficult to use in conjunction with another command without issues):
print("\033[3J")
This can do the same thing that clear used to do (so you can scroll up to see what was deleted, except it doesn't raise the cursor to the top):
print("\033[2J")
If you are on a Linux/UNIX system then printing the ANSI escape sequence to clear the screen should do the job. You will also want to move cursor to the top of the screen. This will work on any terminal that supports ANSI.
import sys
sys.stderr.write("\x1b[2J\x1b[H")
This will not work on Windows unless ANSI support has been enabled. There may be an equivalent control sequence for Windows, but I do not know.
Just use:
print("\033c")
This will clear the terminal window.
You could try to rely on clear but it might not be available on all Linux distributions. On windows use cls as you mentionned.
import subprocess
import platform
def clear():
subprocess.Popen( "cls" if platform.system() == "Windows" else "clear", shell=True)
clear()
Note: It could be considered bad form to take control of the terminal screen. Are you considering using an option? It would probably be better to let the user decide if he want to clear the screen.
Came across this some time ago
def clearscreen(numlines=100):
"""Clear the console.
numlines is an optional argument used only as a fall-back.
"""
# Thanks to Steven D'Aprano, http://www.velocityreviews.com/forums
if os.name == "posix":
# Unix/Linux/MacOS/BSD/etc
os.system('clear')
elif os.name in ("nt", "dos", "ce"):
# DOS/Windows
os.system('CLS')
else:
# Fallback for other operating systems.
print('\n' * numlines)
Then just use clearscreen()
This will be work in Both version Python2 OR Python3
print (u"{}[2J{}[;H".format(chr(27), chr(27)))
A Pure Python solution.
Does not rely on either ANSI, or external commands.
Only your terminal has to have the ability to tell you how many lines are in view.
from shutil import get_terminal_size
print("\n" * get_terminal_size().lines, end='')
Python version >= 3.3.0
So just thought I would throw my two cents in here...
No one has provided a true answer to OP question it seems, everyone either responds with 'NO DONT USE os.system() it's evil!!!' without explanation or provides a solution that relies on printing new lines.
For those that need to clear the terminal screen and scroll back, for whatever reason, you can use the following code:
import os
def clear():
'''
Clears the terminal screen and scroll back to present
the user with a nice clean, new screen. Useful for managing
menu screens in terminal applications.
'''
os.system('cls' if os.name == 'nt' else 'echo -e \\\\033c')
print('A bunch of garbage so we can garble up the screen...')
clear()
# Same effect, less characters...
def clear():
'''
Clears the terminal screen and scroll back to present
the user with a nice clean, new screen. Useful for managing
menu screens in terminal applications.
'''
os.system('cls||echo -e \\\\033c')
This has the OP's desired effect. It does use the os.system() command so if that's evil and someone knows a way of implementing this using subprocess.call() please comment as I would also prefer to use subprocess but am not familiar with it at all.
This function works in gnome-terminal because, by default, it recognizes ANSI escape sequences. It gives you a CLEAN PROMPT rows_max distance from the bottom of the terminal, but also precisely from where it was called. Gives you complete control over how much to clear.
def clear(rows=-1, rows_max=None, *, calling_line=True, absolute=None,
store_max=[]):
"""clear(rows=-1, rows_max=None)
clear(0, -1) # Restore auto-determining rows_max
clear(calling_line=False) # Don't clear calling line
clear(absolute=5) # Absolutely clear out to 5 rows up"""
from os import linesep
if rows_max and rows_max != -1:
store_max[:] = [rows_max, False]
elif not store_max or store_max[1] or rows_max == -1 or absolute:
try:
from shutil import get_terminal_size
columns_max, rows_max = get_terminal_size()
except ImportError:
columns_max, rows_max = 80, 24
if absolute is None:
store_max[:] = [rows_max, True]
if store_max:
if rows == -1:
rows = store_max[0]
elif isinstance(rows, float):
rows = round(store_max[0] * rows)
if rows > store_max[0] - 2:
rows = store_max[0] - 2
if absolute is None:
s = ('\033[1A' + ' ' * 30 if calling_line else '') + linesep * rows
else:
s = '\033[{}A'.format(absolute + 2) + linesep
if absolute > rows_max - 2:
absolute = rows_max - 2
s += (' ' * columns_max + linesep) * absolute + ' ' * columns_max
rows = absolute
print(s + '\033[{}A'.format(rows + 1))
Implementation:
clear() # Clear all, TRIES to automatically get terminal height
clear(800, 24) # Clear all, set 24 as terminal (max) height
clear(12) # Clear half of terminal below if 24 is its height
clear(1000) # Clear to terminal height - 2 (24 - 2)
clear(0.5) # float factor 0.0 - 1.0 of terminal height (0.5 * 24 = 12)
clear() # Clear to rows_max - 2 of user given rows_max (24 - 2)
clear(0, 14) # Clear line, reset rows_max to half of 24 (14-2)
clear(0) # Just clear the line
clear(0, -1) # Clear line, restore auto-determining rows_max
clear(calling_line=False) # Clear all, don't clear calling line
clear(absolute=5) # Absolutely clear out to 5 rows up
Parameters: rows is the number of clear text rows to add between prompt and bottom of terminal, pushing everything up. rows_max is the height of the terminal (or max clearing height) in text rows, and only needs to be set once, but can be reset at any time. *, in the third parameter position means all following parameters are keyword only (e.g., clear(absolute=5)). calling_line=True (default) works better in Interactive mode. calling_line=False works better for text-based, terminal applications. absolute was added to try to fix glitchy gap problems in Interactive mode after reducing size of terminal, but can also be used for terminal applications. store_max is just for secret, "persistent" storage of rows_max value; don't explicitly use this parameter. (When an argument is not passed for store_max, changing the list contents of store_max changes this parameter's default value. Hence, persistent storage.)
Portability: Sorry, this doesn't work in IDLE, but it works >> VERY COOL << in Interactive mode in a terminal (console) that recognizes ANSI escape sequences. I only tested this in Ubuntu 13.10 using Python 3.3 in gnome-terminal. So I can only assume portability is dependant upon Python 3.3 (for the shutil.get_terminal_size() function for BEST results) and ANSI recognition. The print(...) function is Python 3. I also tested this with a simple, text-based, terminal Tic Tac Toe game (application).
For use in Interactive mode: First copy and paste the copy(...) function in Interactive mode and see if it works for you. If so, then put the above function into a file named clear.py . In the terminal start python, with 'python3'. Enter:
>>> import sys
>>> sys.path
['', '/usr/lib/python3.3', ...
Now drop the clear.py file into one of the path directories listed so that Python can find it (don't overwrite any existing files). To easily use from now on:
>>> from clear import clear
>>> clear()
>>> print(clear.__doc__)
clear(rows=-1, rows_max=None)
clear(0, -1) # Restore auto-determining rows_max
clear(calling_line=False) # Don't clear calling line
clear(absolute=5) # Absolutely clear out to 5 rows up
For use in a terminal application: Put the copy(...) function into a file named clear.py in the same folder with your main.py file. Here is a working abstract (skeleton) example from a Tic Tac Toe game application (run from terminal prompt: python3 tictactoe.py):
from os import linesep
class TicTacToe:
def __init__(self):
# Clear screen, but not calling line
try:
from clear import clear
self.clear = clear
self.clear(calling_line=False)
except ImportError:
self.clear = False
self.rows = 0 # Track printed lines to clear
# ...
self.moves = [' '] * 9
def do_print(self, *text, end=linesep):
text = list(text)
for i, v in enumerate(text[:]):
text[i] = str(v)
text = ' '.join(text)
print(text, end=end)
self.rows += text.count(linesep) + 1
def show_board(self):
if self.clear and self.rows:
self.clear(absolute=self.rows)
self.rows = 0
self.do_print('Tic Tac Toe')
self.do_print(''' | |
{6} | {7} | {8}
| |
-----------
| |
{3} | {4} | {5}
| |
-----------
| |
{0} | {1} | {2}
| |'''.format(*self.moves))
def start(self):
self.show_board()
ok = input("Press <Enter> to continue...")
self.moves = ['O', 'X'] * 4 + ['O']
self.show_board()
ok = input("Press <Enter> to close.")
if __name__ == "__main__":
TicTacToe().start()
Explanation: do_print(...) on line 19 is a version of print(...) needed to keep track of how many new lines have been printed (self.rows). Otherwise, you would have to self.rows += 1 all over the place where print(...) is called throughout the entire program. So each time the board is redrawn by calling show_board() the previous board is cleared out and the new board is printed exactly where it should be. Notice self.clear(calling_line=False) on line 9 basically pushes everything up RELATIVE to the bottom of the terminal, but does not clear the original calling line. In contrast, self.clear(absolute=self.rows) on line 29 absolutely clears out everything self.rows distance upward, rather than just pushing everything upward relative to the bottom of the terminal.
Ubuntu users with Python 3.3: Put #!/usr/bin/env python3 on the very first line of the tictactoe.py file. Right click on the tictactoe.py file => Properties => Permissions tab => Check Execute: Allow executing file as program. Double click on the file => Click Run in Terminal button. If an open terminal's current directory is that of the tictactoe.py file, you can also start the file with ./tictactoe.py.
If you wish to clear your terminal when you are using a python shell. Then, you can do the following to clear the screen
import os
os.system('clear')
In Windows you can use:
>>> import os
>>> clear = lambda: os.system('cls')
>>> clear()
You could tear through the terminfo database, but the functions for doing so are in curses anyway.
python -c "from os import system; system('clear')"
You can use call() function to execute terminal's commands :
from subprocess import call
call("clear")
you can make your own. this will not be dependent on your terminal, or OS type.
def clear(num):
for i in range(num): print
clear(80)
print "hello"
This will clear 25 new lines:
def clear():
print(' \n' * 25)
clear()
I use eclipse with pydev. I like the newline solution better than the for num in range . The for loop throws warnings, while the print newline doesn't.
If you want to specify the number of newlines in the clear statement try this variation.
def clear(j):
print(' \n' * j)
clear(25)
If all you need is to clear the screen, this is probably good enough. The problem is there's not even a 100% cross platform way of doing this across linux versions. The problem is the implementations of the terminal all support slightly different things. I'm fairly sure that "clear" will work everywhere. But the more "complete" answer is to use the xterm control characters to move the cursor, but that requires xterm in and of itself.
Without knowing more of your problem, your solution seems good enough.
A perhaps cheesy way to clear the screen, but one that will work on any platform I know of, is as follows:
for i in xrange(0,100):
print ""
I would do it in this way to make it look more like bash:
Just create a file named .pythonstartup at Home directory and use poke's answer in a function
On Linux:
echo "from subprocess import call
def clear(int=None):
call('clear')
if int == 0:
exit()
clear()" >> $HOME/.pythonstartup ; export PYTHONSTARTUP=$HOME/.pythonstartup ; python
You can add export PYTHONSTARTUP=$HOME/.pythonstartup to your ./bashrc file
Since what I care about is space; a call to the function will not display the python interpreter description at startup, but you can remove clear() to retain it.
Using it like a normal function should do the trick without printing the exit status:
>>> clear()
If you pass the argument 0 to the function it will clear the screen and exit successfully so you can continue using the shell in a clean screen
>>> clear(0)
For Windows, on the interpreter command line only (not the GUI)! Simply type:
(Remember to use proper indentation with python):
import os
def clear():
os.system('cls')
Every time you type clear() on the shell (command line), it will clear the screen on your shell. If you exit the shell, then you must redo the above to do it again as you open a new Python (command line) shell.
Note: Does not matter what version of Python you are using, explicitly (2.5, 2.7, 3.3 & 3.4).
The accepted answer is a good solution. The problem with it is that so far it only works on Windows 10, Linux and Mac. Yes Windows (known for it lack of ANSI support)! This new feature was implemented on Windows 10 (and above) which includes ANSI support, although you have to enable it. This will clear the screen in a cross platform manner:
import os
print ('Hello World')
os.system('')
print ("\x1B[2J")
On anything below Windows 10 however it returns this:
[2J
This is due to the lack of ANSI support on previous Windows builds. This can however, be solved using the colorama module. This adds support for ANSI characters on Windows:
ANSI escape character sequences have long been used to produce colored terminal text and cursor positioning on Unix and Macs. Colorama makes this work on Windows, too, by wrapping stdout, stripping ANSI sequences it finds (which would appear as gobbledygook in the output), and converting them into the appropriate win32 calls to modify the state of the terminal. On other platforms, Colorama does nothing.
So here is a cross platform method:
import sys
if sys.platform == 'win32':
from colorama import init
init()
print('Hello World')
print("\x1B[2J")
Or print(chr(27) + "[2J") used instead of print("\x1B[2J").
#poke answer is very insecure on Windows, yes it works but it is really a hack. A file named cls.bat or cls.exe in the same dictionary as the script will conflict with the command and execute the file instead of the command, creating a huge security hazard.
One method to minimise the risk could be to change the location of where the cls command is called:
import os
os.system('cd C:\\Windows|cls' if os.name == 'nt' else 'clear')
This will change the Currant Dictionary to C:\Window (backslash is important here) then execute. C:\Windows is always present and needs administration permissions to write there making it a good for executing this command with minimal risk. Another solution is to run the command through PowerShell instead of Command Prompt since it has been secured against such vulnerabilities.
There are also other methods mentioned in this question: Clear screen in shell which may also be of use.
By default, os.system("clear")/os.system("cls") will return an int type as 0.
We can completely clear the screen by assigning it to a variable and deleting that.
def clear():
if (os.name == 'nt'):
c = os.system('cls')
else:
c = os.system('clear')
del c # can also omit c totally
#clear()
This works on all platforms and it does work in both Python 2 and 3.
def clear(number):
for i in range(number):
print(" ")
Then to clear just type clear(numberhere).

Running a .py file in a loop

I am currently trying to run a .py file but in a loop.
Just for a test I am using
I = 0
while I<10:
os.pause(10)
open(home/Tyler/desktop/test.py)
I = I + 1
I am sure this is a very simple question but I can't figure this one out.
I would also like to add in the very end of this I have to make this run infinitely and let it run for some other things.
There are a few reasons why your code isn't working:
Incorrect indentation (this may just be how you copied it on to StackOverflow though).
Using os without importing it.
Not using quotes for a string.
Mis-using the open function; open opens a file for reading and/or writing. To execute a file you probably want to use the os.system.
Here's a version that should work:
import os
i = 0
while i < 10:
os.pause(10)
os.system("home/Tyler/desktop/test.py")
i += 1
Python is indentation-sensitive, and your code is missing indentation
after the while statement!
Running the open command will not run the Python script. You can
read what it does here in the docs:
https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files
This stack overflow question talks about how to run Python that's
stored in another file
How can I make one python file run another?
I recommend wrapping the code you want to run in a function, e.g.
def foo():
print 'hello'
and then saving this in foo.py. From your main script, you can then do:
import foo
i = 0
while i < 10:
foo.foo()
i += 1
If you want to run something in an infinite loop, you need the condition for the while loop to always be true:
while True:
# do thing forever
A note on importing: The example I have given will work if the foo.py file is in the same directory as the main Python file. If it is not, then you should have a read here about how to create Python modules http://www.tutorialspoint.com/python/python_modules.htm

Run .py file until specified line number

In a linux terminal typing
python script.py
Will run run script.py and exit the python console, but what if I just want to run a part of the script and leave the console open? For example, run script.py until line 15 and leave the console open for further scripting. How would I do this?
Let's say it's possible, then with the console still open and script.py run until line 15, can I then from inside the console call line fragments from other py files?
...something like
python script.py 15 #(opens script and runs lines 1-15 and leaves console open)
Then having the console open, I would like to run lines 25-42 from anotherscript.py
>15 lines of python code run from script.py
> run('anotherscript.py', lines = 25-42)
> print "I'm so happy the console is still open so I can script some more")
I'm so happy the console is still open so I can script some more
>
Your best bet might be pdb, the Python debugger. You can start you script under pdb, set a breakpoint on line 15, and then run your script.
python -m pdb script.py
b 15 # <-- Set breakpoint on line 15
c # "continue" -> run your program
# will break on line 15
You can then inspect your variables and call functions. Since Python 3.2, you can also use the interact command inside pdb to get a regular Python shell at the current execution point!
If that fits your bill and you also like IPython, you can check out IPdb, which is a bit nicer than normal pdb, and drops you into an IPython shell with interact.
if you want to run script.py from line a to line b, simply use this bash snippet:
cat script.py|head -{a+b}|tail -{b-a}|python -i
replace {a+b} and {b-a} with their values
You could use the python -i option to leave the console open at the end of the script.
It lets your script run until it exits, and you can then examine variables, call any function and any Python code, including importing and using other modules.
Of course your script needs to exit first, either at the end or, if your goal is to debug that part of the script, you could add a sys.exit() or os._exit() call where you want it to stop (such as your line 15).
For instance:
import os
print "Script starting"
a=1
def f(x):
return x
print "Exiting on line 8"
os._exit(0) # to avoid the standard SystemExit exception
print "Code continuing"
Usage example:
python -i test_exit.py
Scrit starting
Exiting on line 8
>>> print a
1
>>> f(4)
4
>>>
You cannot do that directly but you can do something similar from inside Python console (or IDLE) with exec :
just open you favorite Python console
load wanted lines into a string and exec them :
script = 'script.py'
txt = ''
with open(script) as sc:
for i, line in enumerate(sc):
if i >= begline and i<= endline:
txt = txt + line
exec(txt)
You can even write your own partial script runner based on that code ...
EDIT
I must admit that above answer alone really deserved to be downvoted. It is technically correct and probably the one that most closely meet what you asked for. But I should have warned you that it is bad pratice. Relying on line numbers to load pieces of source files is error prone and you should avoid it unless you really know what you are doing and why you do it that way. Python debugger at least allows you to control what are the lines you are about to execute.
If you really have to use this solution be sure to always print and double check the lines that you are about to execute. IMHO it is always both simpler and safer to copy and past lines in an IDE like IDLE that is packaged into any standard Python installation.

processing stdout in python

I have a script that keeps on dumping some values to the screen. Lets call this script 1
I need the values that gets dumped to the screen to be processed by another python script.Lets call this script2. I Script1 cant be stopped
I currently use python 2.2 so it would be great if someone could provide an example without using subprocess
script 1 looks something like this
import sys
import os
i = 0
while 1:
print i
sys.stdout.write(str(i)+"\n")
i = i + 1
I need to write script2 such that every output generated by script1 is processed by script2
-- edit --
I need it to run on a legacy implementation ie no power shell just the command prompt available in Windows XP
I'm not going to say anything about code design here, because I really don't know what you are working on.
But for script2.py:
import sys
for line in sys.stdin:
print "From stdin:", line
And then run (at least on unix/linux, if you are on windows, google "piping in powershell"):
python script1.py | python script2.py
Or did you want to do it within one python script? You could re-pipe sys.stdout, by simply replacing it with a class that has all the necessary methods (write, etc.).
I guess you want to process line by line:
# script2.py
import sys
for line in sys.stdin:
print line # do something here with line
[edit] Finally, you simply pipe them:
python script1.py | python script2.py

Categories

Resources