Print to terminal window in python - python

I am trying to debug my code and see if I am entering a loop when I should. I am running this on a Linux server. The python script gets executed via website. I want to print something to the terminal window to let me know I entered the loop. I have been trying:
proc = subprocess.Popen(["echo" + "Statement"])
How do you print to the terminal window through a python script?

Casual print() should do it in case you run the server from the terminal window.
Otherwise, you need to pipe output somewhere, probably to file like this
import sys
sys.stdout = open('/tmp/server.log', 'w')
and then in your terminal window do
tail -f /tmp/server.log
which will hook to the file and print any changes, therefore getting effect you wanted.

Related

Python subprocess.run C Program not working

I am trying to write the codes to run a C executable using Python.
The C program can be run in the terminal just by calling ./myprogram and it will prompt a selection menu, as shown below:
1. Login
2. Register
Now, using Python and subprocess, I write the following codes:
import subprocess
subprocess.run(["./myprogram"])
The Python program runs but it shows nothing (No errors too!). Any ideas why it is happening?
When I tried:
import subprocess
subprocess.run(["ls"])
All the files in that particular directory are showing. So I assume this is right.
You have to open the subprocess like this:
import subprocess
cmd = subprocess.Popen(['./myprogram'], stdin=subprocess.PIPE)
This means that cmd will have a .stdin you can write to; print by default sends output to your Python script's stdout, which has no connection with the subprocess' stdin. So do that:
cmd.stdin.write('1\n') # tell myprogram to select 1
and then quite probably you should:
cmd.stdin.flush() # don't let your input stay in in-memory-buffers
or
cmd.stdin.close() # if you're done with writing to the subprocess.
PS If your Python script is a long-running process on a *nix system and you notice your subprocess has ended but is still displayed as a Z (zombie) process, please check that answer.
Maybe flush stdout?
print("", flush=True,end="")

How to use Python subprocess to write multiple inputs into custom exe program

I am trying to open a executable that opens a HEC .dss database file. However, I can only seem to get it to read one argument after opening the exe and then it doesn't read anything else. Is there any way to force it to keep inserting commands.
This exe has some unique features to it, which include that the first command asks what DSS file you are going to read. Then you can input a command to create the output txt file that it will write to for the rest of the commands. What I've been able to do so far is to start the program and run one command into the exe (the mydss variable). However, after that first command is read, none of the other commands are used in the command prompt. I feel like I'm missing something here. Here is the code:
##Testing on how to run and use the DSSUTL program
import subprocess
from subprocess import PIPE, STDOUT
DSSUTL = "C:\Users\sduncan\Documents\HEC-DSS\HEC-DSSVue-2_0_1\FromSivaSel\DSSUTL.exe"
mydss = "C:\Users\sduncan\Documents\HEC-DSS\HEC-DSSVue-2_0_1\FromSivaSel\\forecast.dss"
firstLine = "WR.T TO=PythonTextOutput.txt"
commandLine = "WR.T B=SHAVER RESERVOIR-POOL C=FLOW-IN E=1HOUR F=10203040"
myList = [firstLine, commandLine]
ps = subprocess.Popen([DSSUTL, mydss, myList[1], myList[0]], shell=True)
I've also tried including stdin=subprocess.PIPE, but that only leads to the exe opening and it is blank (when I open it with the code above I can read it and see that the mydss variable was read correctly). When I used stdout or sterr, the program only opens and closes.
I've also tried using the code when the stdin=PIPE was turned on with:
ps.stdin.write(myList[1])
ps.stdin.write(myList[0])
ps.communicate()[0]
However, it did not read anything in the program. This program runs like a command prompt, however, it's not the typical cmd as it was made to read the DSS filetype and produce a text file with the list from searches like in the commandLine variable
It would be nice to know what I could do to fix the code so that I could input the extra commands. Any help to know how to event check if the commands were being sent or processed by this exe. Eventually, I will be adding many more commands to the exe file to print to the text file, so if there is any way to get python to write to the exe that would help.
#tdelaney, #eryksun Thank you for commenting, your comments about the pipes and delay really helped. I was able to fix the problem by using this code:
##Testing on how to run and use the DSSUTL program
import subprocess
from subprocess import PIPE, STDOUT
import time
DSSUTL = "C:\Users\sduncan\Documents\HEC-DSS\HEC-DSSVue-2_0_1\FromSivaSel\DSSUTL.exe"
mydss = "C:\Users\sduncan\Documents\HEC-DSS\HEC-DSSVue-2_0_1\FromSivaSel\\forecast.dss"
location = "WR.T TO=PythonTextOutput.txt" + " WR.T B=SHAVER RESERVOIR-POOL C=FLOW-IN E=1HOUR F=10203040" + "\n"
filecontent1 = "WR.T B=FLORENCE RESERVOIR-POOL C=FLOW-IN E=1HOUR F=10203040" + "\n"
filecontent2 = "WR.T B=HUNTINGTON LAKE-POOL C=FLOW-IN E=1HOUR F=10203040" + "\n"
filecontentList = [filecontent1, filecontent2]
myList = [DSSUTL, mydss] # commandLine, location
ps = subprocess.Popen(myList , shell=False, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
time.sleep(1)
# input into stdin
ps.stdin.write(location)
time.sleep(1)
ps.stdin.write(filecontent1)
time.sleep(1)
ps.stdin.write(filecontent2)
time.sleep(1)
print ps.communicate()[0]
# End Script
By using the pipes to talk to the program and putting a time delay seemed to fix the problem and allowed me to talk to the console. Even though the console display is blank, by printing the communicate() command, it outputs what the console did and produce the text file with the wanted series.
Thanks for pushing me in the right direction!

Python: Spawn New Minimized Shell

I am attempting to to launch a python script from within another python script, but in a minimized console, then return control to the original shell.
I am able to open the required script in a new shell below, but it's not minimized:
#!/usr/bin/env python
import os
import sys
import subprocess
pyTivoPath="c:\pyTivo\pyTivo.py"
print "Testing: Open New Console"
subprocess.Popen([sys.executable, pyTivoPath], creationflags = subprocess.CREATE_NEW_CONSOLE)
print
raw_input("Press Enter to continue...")
Further, I will need to be able to later remotely KILL this shell from the original script, so I suspect I'll need to be explicit in naming the new process. Correct?
Looking for pointers, please. Thanks!
Note: python27 is mandatory for this application. Eventually will also need to work on Mac and Linux.
Do you need to have the other console open? If you now the commands to be sent, then I'd recommend using Popen.communicate(input="Shell commands") and it will automate the process for you.
So you could write something along the lines of:
# Commands to pass into subprocess (each command is separated by a newline)
commands = (
"command1\n" +
"command2\n"
)
# Your process
py_process = subprocess.Popen(*yourprocess_here*, stdin=PIPE, shell=True)
# Feed process the needed input
py_process.communicate(input=commands)
# Terminate when finished
py_process.terminate()
The code above will execute the process you specify and even send commands but it won't open a new console.

Want to resize terminal windows in python, working but not quite right

I'm attempted to resize the terminal window on launch of a python script to ensure the display will be static size. It's working but not quite what I expected. I've tried a few methods:
import sys
sys.stdout.write("\x1b[8;40;120t")
and
import subprocess
subprocess.call(["echo","-e","\x1b[8;40;120t"])
and even just
print "\x1b[8;40;80t"
They all work and resize the real terminal. However, if my terminal is, let's say 25x80 to start, the script starts, it resizes, then exits. It will not execute the rest of the script. I wrapped it in a try/Except and nothing is thrown. Nothing in the syslogs and python -v script.py shows nothing odd. If I execute the script again or at a term size of 40x120 (my target size)..the script runs just fine. Why is exeecuting the ANSI escape exiting python? Furthermore if I run this interactively it works with no issues.
Using Python 2.6.6.
I tried to run the following script, and it "works" (Linux Debian / Python 2.6 / gnome-terminal):
print "\x1b[8;40;80t"
print "ok"
The window is resized and the script execution continue.
If you confirm in your case the program stops after resizing, my guess would be Python received a signal SIGWINCH when the window is resized.
You should try to add a specific signal handler. Something like that:
def resizeHandler(signum, frame):
print "resize-window signal caught"
signal.signal(signal.SIGWINCH, resizeHandler)
You need to put the terminal in cbreak mode for this. Using the term package (easy_install term) this could look like this:
from term import opentty, cbreakmode
with opentty() as tty:
if tty is not None:
with cbreakmode(tty, min=0):
tty.write('\033[8;26;81t');
print 'terminal resized'

How to keep a Python script output window open?

I have just started with Python. When I execute a python script file on Windows, the output window appears but instantaneously goes away. I need it to stay there so I can analyze my output. How can I keep it open?
You have a few options:
Run the program from an already-open terminal. Open a command prompt and type:
python myscript.py
For that to work you need the python executable in your path. Just check on how to edit environment variables on Windows, and add C:\PYTHON26 (or whatever directory you installed python to).
When the program ends, it'll drop you back to the cmd prompt instead of closing the window.
Add code to wait at the end of your script. For Python2, adding ...
raw_input()
... at the end of the script makes it wait for the Enter key. That method is annoying because you have to modify the script, and have to remember removing it when you're done. Specially annoying when testing other people's scripts. For Python3, use input().
Use an editor that pauses for you. Some editors prepared for python will automatically pause for you after execution. Other editors allow you to configure the command line it uses to run your program. I find it particularly useful to configure it as "python -i myscript.py" when running. That drops you to a python shell after the end of the program, with the program environment loaded, so you may further play with the variables and call functions and methods.
cmd /k is the typical way to open any console application (not only Python) with a console window that will remain after the application closes. The easiest way I can think to do that, is to press Win+R, type cmd /k and then drag&drop the script you want to the Run dialog.
Start the script from an already open cmd window or
at the end of the script add something like this, in Python 2:
raw_input("Press enter to exit;")
Or, in Python 3:
input("Press enter to exit;")
To keep your window open in case of exception (yet, while printing the exception)
Python 2
if __name__ == '__main__':
try:
## your code, typically one function call
except Exception:
import sys
print sys.exc_info()[0]
import traceback
print traceback.format_exc()
print "Press Enter to continue ..."
raw_input()
To keep the window open in any case:
if __name__ == '__main__':
try:
## your code, typically one function call
except Exception:
import sys
print sys.exc_info()[0]
import traceback
print traceback.format_exc()
finally:
print "Press Enter to continue ..."
raw_input()
Python 3
For Python3 you'll have to use input() in place of raw_input(), and of course adapt the print statements.
if __name__ == '__main__':
try:
## your code, typically one function call
except BaseException:
import sys
print(sys.exc_info()[0])
import traceback
print(traceback.format_exc())
print("Press Enter to continue ...")
input()
To keep the window open in any case:
if __name__ == '__main__':
try:
## your code, typically one function call
except BaseException:
import sys
print(sys.exc_info()[0])
import traceback
print(traceback.format_exc())
finally:
print("Press Enter to continue ...")
input()
you can combine the answers before: (for Notepad++ User)
press F5 to run current script and type in command:
cmd /k python -i "$(FULL_CURRENT_PATH)"
in this way you stay in interactive mode after executing your Notepad++ python script and you are able to play around with your variables and so on :)
Create a Windows batch file with these 2 lines:
python your-program.py
pause
Using atexit, you can pause the program right when it exits. If an error/exception is the reason for the exit, it will pause after printing the stacktrace.
import atexit
# Python 2 should use `raw_input` instead of `input`
atexit.register(input, 'Press Enter to continue...')
In my program, I put the call to atexit.register in the except clause, so that it will only pause if something went wrong.
if __name__ == "__main__":
try:
something_that_may_fail()
except:
# Register the pause.
import atexit
atexit.register(input, 'Press Enter to continue...')
raise # Reraise the exception.
In python 2 you can do it with: raw_input()
>>print("Hello World!")
>>raw_input('Waiting a key...')
In python 3 you can do it with: input()
>>print("Hello world!")
>>input('Waiting a key...')
Also, you can do it with the time.sleep(time)
>>import time
>>print("The program will close in 5 seconds")
>>time.sleep(5)
On Python 3
input('Press Enter to Exit...')
Will do the trick.
You can just write
input()
at the end of your code
therefore when you run you script it will wait for you to enter something
{ENTER for example}
I had a similar problem. With Notepad++ I used to use the command : C:\Python27\python.exe "$(FULL_CURRENT_PATH)" which closed the cmd window immediately after the code terminated.
Now I am using cmd /k c:\Python27\python.exe "$(FULL_CURRENT_PATH)" which keeps the cmd window open.
To just keep the window open I agree with Anurag and this is what I did to keep my windows open for short little calculation type programs.
This would just show a cursor with no text:
raw_input()
This next example would give you a clear message that the program is done and not waiting on another input prompt within the program:
print('You have reached the end and the "raw_input()" function is keeping the window open')
raw_input()
Note!
(1) In python 3, there is no raw_input(), just
input().
(2) Use single quotes to indicate a string; otherwise if you type doubles around anything, such as
"raw_input()", it will think it is a function, variable, etc, and not text.
In this next example, I use double quotes and it won't work because it thinks there is a break in the quotes between "the" and "function" even though when you read it, your own mind can make perfect sense of it:
print("You have reached the end and the "input()" function is keeping the window open")
input()
Hopefully this helps others who might be starting out and still haven't figured out how the computer thinks yet. It can take a while. :o)
If you want to run your script from a desktop shortcut, right click your python file and select Send to|Desktop (create shortcut). Then right click the shortcut and select Properties. On the Shortcut tab select the Target: text box and add cmd /k in front of the path and click OK. The shortcut should now run your script without closing and you don't need the input('Hit enter to close')
Note, if you have more than one version of python on your machine, add the name of the required python executable between cmd /k and the scipt path like this:
cmd /k python3 "C:\Users\<yourname>\Documents\your_scipt.py"
Apart from input and raw_input, you could also use an infinite while loop, like this:
while True: pass (Python 2.5+/3) or while 1: pass (all versions of Python 2/3). This might use computing power, though.
You could also run the program from the command line. Type python into the command line (Mac OS X Terminal) and it should say Python 3.?.? (Your Python version) It it does not show your Python version, or says python: command not found, look into changing PATH values (enviromentl values, listed above)/type C:\(Python folder\python.exe. If that is successful, type python or C:\(Python installation)\python.exe and the full directory of your program.
A very belated answer, but I created a Windows Batch file called pythonbat.bat containing the following:
python.exe %1
#echo off
echo.
pause
and then specified pythonbat.bat as the default handler for .py files.
Now, when I double-click a .py file in File Explorer, it opens a new console window, runs the Python script and then pauses (remains open), until I press any key...
No changes required to any Python scripts.
I can still open a console window and specify python myscript.py if I want to...
(I just noticed #maurizio already posted this exact answer)
If you want to stay cmd-window open AND be in running-file directory this works at Windows 10:
cmd /k cd /d $(CURRENT_DIRECTORY) && python $(FULL_CURRENT_PATH)
I found the solution on my py3 enviroment at win10 is just run cmd or powershell as Administrator,and the output would stay at the same console window,any other type of user run python command would cause python to open a new console window.
The simplest way:
your_code()
while True:
pass
When you open the window it doesn't close until you close the prompt.
`import sys,traceback
sys.exc_info()[0]
traceback.format_exc()
print("Press Enter to exit ...")
input()`
simply write the above code after your actual code. for eg. am taking input from user and print on console hence my code will be look like this -->
`import sys,traceback
nam=input("enter your name:")
print("your name is:-{}".format(nam)) #here all my actual working is done
sys.exc_info()[0]
traceback.format_exc()
print("Press Enter to exit ...")
input()`
Try this,
import sys
stat='idlelib' in sys.modules
if stat==False:
input()
This will only stop console window, not the IDLE.
You can launch python with the -i option or set the environment variable PYTHONINSPECT=x. From the docs:
inspect interactively after running script; forces a prompt even
if stdin does not appear to be a terminal; also PYTHONINSPECT=x
So when your script crashes or finishes, you'll get a python prompt and your window will not close.
Create a function like dontClose() or something with a while loop:
import time
def dontClose():
n = 1
while n > 0:
n += 1
time.sleep(n)
then run the function after your code. for e.g.:
print("Hello, World!")
dontClose()
Go here and download and install Notepad++
Go here and download and install Python 2.7 not 3.
Start, Run Powershell. Enter the following. [Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27", "User")
Close Powershell and reopen it.
Make a directory for your programs. mkdir scripts
Open that directory cd scripts
In Notepad++, in a new file type: print "hello world"
Save the file as hello.py
Go back to powershell and make sure you are in the right directory by typing dir. You should see your file hello.py there.
At the Powershell prompt type: python hello.py
On windows 10 insert at beggining this:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
Strange, but it work for me!(Together with input() at the end, of course)
You can open PowerShell and type "python".
After Python has been imported, you can copy paste the source code from your favourite text-editor to run the code.
The window won't close.
A simple hack to keep the window open:
counter = 0
While (True):
If (counter == 0):
# Code goes here
counter += 1
The counter is so the code won’t repeat itself.
The simplest way:
import time
#Your code here
time.sleep(60)
#end of code (and console shut down)
this will leave the code up for 1 minute then close it.

Categories

Resources