Get previous console output as string in script - python

I have a script that returns an output in the console, eg (not the actual code just an example):
print("Hello World")
I want to be able to catch this output as a string and store it as a variable:
print("Hello World")
# function to catch previous line output and store it as a variable

I'm assuming by the wording in your question that you are running the first print command in a different script than the first one. In that case you can run it using the subprocess module and catch the output like this:
from subprocess import run
result = run(['script.py'], capture_output=True)
previous_output = result.stdout

You can just do that
a = "Hello World !"
print(a)
it's easier than trying to capture it after printing the actual string, but if you insist,
#Blupper already answered your question.

Related

Any way to stop a command from returning exit codes? [duplicate]

I've got a Python script that uses os.system to run shell commands. The output from those commands is echoed to the screen; I like this and need to keep it. I would also like my script to be able to take action based on the contents of the output from the system call. How can I do this?
In my specific case, I'm calling os.system("svn update"). I need the output to go to the screen and (in case of conflicts, for example), the user needs to be able to interact with svn. I would like to be able to have the script take action based on the output - to trigger a build if it sees that a build script was updated, for example.
I'd prefer not to handle the I/O myself (that would seem unnecessarily complex) and I'd rather not send the output to a temporary file that I have to clean up later (though I will if I must).
Edit:
Here's my test script:
#!/usr/bin/python -t
import subprocess
output = subprocess.check_output(["echo","one"])
print "python:", output
output = subprocess.check_output(["echo", "two"], shell=True)
print "python:", output
output = subprocess.check_output("echo three", shell=True)
print "python:", output
and here's its output:
$ ./pytest
python: one
python:
python: three
(There's an extra blank line at the end that the code block doesn't show.) I expect something more like:
$ ./pytest
one
python: one
two
python:
three
python: three
To run a process, I would look into subprocess.check_output. In this case, something like:
output = subprocess.check_output(['svn','update'])
print output
This only works on python2.7 or newer though. If you want a version which works with older versions of python:
p = subprocess.Popen(['svn','update'],stdout=subprocess.PIPE)
output,stderr = p.communicate()
print output

How do you connect two command words in python?

import os
blah = 'Umm'
print('blah')
os.system('say blah')
"""so I want to make these two things linked,
so that whenever I print something, it says that something
"""
I wanna link these two things, so that whenever I call upon print() it also says what I printed.
Please excuse my (possible) misuse of terminology.
You need to wrap it in a function, then its just a simple case of finding and replacing all of your print with printSay
import os
def printSay(word):
print(word)
os.system('say {word}'.format(word=word))
# Usage
printSay("Hello")
You could run say as a subprocess and write the data to its stdin. I did this on linux with espeak, but I think I got the say command right.
import subprocess
say = subprocess.Popen(["say", "-f", "-"], stdin=subprocess.PIPE)
def myprint(*args):
print(*args)
say.stdin.write((' '.join(args) + '\n').encode('utf-8'))
myprint("hello there")

Capture return value from python

I have a shell script TestNode.sh. This script has content like this:
port_up=$(python TestPorts.py)
python TestRPMs.py
Now, I want to capture the value returned by these scripts.
TestPorts.py
def CheckPorts():
if PortWorking(8080):
print "8080 working"
return "8080"
elif PortWorking(9090):
print "9090 working"
return "9090"
But as I checked the answers available, they are not working for me. The print is pushing the value in variable port_up, but I wanted that print should print on the console and the variable port_up should get the value from return statement. Is there a way to achieve this?
Note: I don't wish to use sys.exit(). Is it possible to achieve the same without this?
but I wanted that print should print on the console and the variable port_up should get the value from return statement.
Then don't capture the output. Instead do:
python TestPorts.py
port_up=$? # return value of the last statement
python TestRPMs.py
You could do:
def CheckPorts():
if PortWorking(8080):
sys.stderr.write("8080 working")
print 8080
But then I am not very happy to print "output" to stderr either.
Alternatively, you could skip printing that "8080 working" message in python script and print it from the shell script.
def CheckPorts():
if PortWorking(8080):
return "8080"
and:
port_up=$(python TestPorts.py)
echo "$port_up working"
python TestRPMs.py
To return an exit code from a Python script you can use sys.exit(); exit() may also work. In the Bash (and similar) shell, the exit code of the previous command can be found in $?.
However, the Linux shell exit codes are 8 bit unsigned integers, i.e. in the range 0-255, as mentioned in this answer. So your strategy isn't going to work.
Perhaps you can print "8080 working" to stderr or a logfile and print "8080" to stdout so you can capture it with $().

Python run command and capture result - do not print result to screen

I'm trying to run a command from a python script, but I want to store the output the command produces and then check it for a substring, however it seems it is not being stored in my variable because it still prints to the screen.
So far I have this...
myfile = 'filename.txt'
result = subprocess.Popen(['myprogram.exe', '-f' + myfile], stdout=subprocess.PIPE).communicate()[0]
if result.find("error executing") != -1:
print "error!"
else:
print "success!"
I'm rather new to Python. Can anyone shed some light on WHY when I run this script, the myprogram.exe DOES execute, but it's output is still sent to the screen. If I print the result variable, it DOES have additional output from myprogram.exe, but I need the lines that show the error too.
You're only redirecting stdout. Looks like your program outputs errors to stderr (as expected), add stderr=subprocess.PIPE to the Popen call.

print statements only appearing before or after a subprocess call

This question is related to Python: why print statements and subprocess.call() output are out of sync? but the solutions are not working for my particular situation. I am trying to accomplish an automation test process in python that has first prints the name of a Test Suite, then has a for loop which iterate through a list printing the name of a particular test, followed by a subprocess call to execute the test, ended with a print statement that the test is finished. Lastly, I print a statement that says it is the end of the test suite name.
i.e.
=========BEGIN TEST SUITE: =========
---------start test: ----------
subprocess call to execute test
---------end test: ------------
repeat for tests
=========END TEST SUITE: ==========
My current code works fine but when I redirect its output to a file, it puts all the print statements at the bottom. When using the solutions in the other question, it does the complete opposite for me and prints all the print statements first, then executes the test. I tried used the sys.stdout.flush(), as well as turning off the buffering but both give me the same thing. How can I get everything to be printed exactly the way it executes/is in the code when I redirect output or write to a file??
The way I generally solve problems like this is to capture the output in the python program and print it when I want it to print using a Popen
>>> def do_ls():
... print "I'm about to ls"
... ls = subprocess.Popen('ls', stdout=subprocess.PIPE)
... output = ls.communicate()[0] #wait for the process to finish, capture stdout
... print 'ls output:'
... print output
... print 'done.'
I can show you how to do this more specifically for your tests if you post some code

Categories

Resources