Getting output from "print" inside a function [duplicate] - python

This question already has answers here:
Can I redirect the stdout into some sort of string buffer?
(9 answers)
capturing dis.dis results
(2 answers)
Closed 8 years ago.
Im using a library of functions that some of them print data I need:
def func():
print "data"
How can I call this function and get the printed data into a string?

If you can't change those functions, you will need to redirect sys.stdout:
>>> import sys
>>> stdout = sys.stdout
>>> import StringIO
>>> s = StringIO.StringIO()
>>> sys.stdout = s
>>> print "hello"
>>> sys.stdout = stdout
>>> s.seek(0)
>>> s.read()
'hello\n'

Related

Read string from html code and save to file [duplicate]

This question already has answers here:
Converting special characters to regular c#
(4 answers)
Closed 2 years ago.
How do I translate the bytes %C3%B8 in "testdoc%C3%B8%C3%B8%C3%B8.txt" to ø?
I tried the following which did not work:
var cont = response.Content.Headers.ContentDisposition?.FileName;
var bytes = Encoding.UTF8.GetBytes(cont);
var test = new string(bytes.Select(b => (char)b).ToArray());
var yourText = System.Text.Encoding.UTF8.GetString(bytes);
Don't bother with converting it to bytes at all. As has been noted in the comments, this is URL encoding, not UTF8.
Use HttpUtility in the System.Web namespace:
string input = "testdoc%C3%B8%C3%B8%C3%B8.txt";
string output = HttpUtility.UrlDecode(input);
Console.WriteLine(output); // testdocøøø.txt
Try it online

printf formatting of strings in python [duplicate]

This question already has answers here:
How to reset cursor to the beginning of the same line in Python
(6 answers)
Closed 5 years ago.
Is there a way to do printf formatting to strings in Python? Something like this where the count x is rewritten every time instead of echoing to a new line.
x=0
while [[ $x -lt 10 ]]; do
x=$((x+1))
printf '%s\r'"Processing page ${x}"
sleep 1
done
In Python 3.x, the print function takes in an additional argument for the end parameter.
>>> print('foo', end='')
foo
>>> for i in range(10):
print('foo', end='')
foofoofoofoofoofoofoofoofoofoo
Of course, if you're using Python >= 2.6, you'll need to import print_function from __future__.
>>> from __future__ import print_function
In Python 3 (Daiwei Chen's answer covers Python 2.6+ also):
import time
x = 0
while x < 10:
x += 1
print('\rProcessing Page {0}'.format(x), end='')
time.sleep(1)
Adding a carriage return to the beginning and removing the new line from the end with end='' will overwrite the current line.

Bug in StringIO module python using numpy

Very simple code:
import StringIO
import numpy as np
c = StringIO.StringIO()
c.write("1 0")
a = np.loadtxt(c)
print a
I get an empty array + warning that c is an empty file.
I fixed this by adding:
d=StringIO.StringIO(c.getvalue())
a = np.loadtxt(d)
I think such a thing shouldn't happen, what is happening here?
It's because the 'position' of the file object is at the end of the file after the write. So when numpy reads it, it reads from the end of the file to the end, which is nothing.
Seek to the beginning of the file and then it works:
>>> from StringIO import StringIO
>>> s = StringIO()
>>> s.write("1 2")
>>> s.read()
''
>>> s.seek(0)
>>> s.read()
'1 2'
StringIO is a file-like object. As such it has behaviors consistent with a file. There is a notion of a file pointer - the current position within the file. When you write data to a StringIO object the file pointer is adjusted to the end of the data. When you try to read it, the file pointer is already at the end of the buffer, so no data is returned.
To read it back you can do one of two things:
Use StringIO.getvalue() as you already discovered. This returns the
data from the beginning of the buffer, leaving the file pointer unchanged.
Use StringIO.seek(0) to reposition the file pointer to the start of
the buffer and then calling StringIO.read() to read the data.
Demo
>>> from StringIO import StringIO
>>> s = StringIO()
>>> s.write('hi there')
>>> s.read()
''
>>> s.tell() # shows the current position of the file pointer
8
>>> s.getvalue()
'hi there'
>>> s.tell()
8
>>> s.read()
''
>>> s.seek(0)
>>> s.tell()
0
>>> s.read()
'hi there'
>>> s.tell()
8
>>> s.read()
''
There is one exception to this. If you provide a value at the time that you create the StringIO the buffer will be initialised with the value, but the file pointer will positioned at the start of the buffer:
>>> s = StringIO('hi there')
>>> s.tell()
0
>>> s.read()
'hi there'
>>> s.read()
''
>>> s.tell()
8
And that is why it works when you use
d=StringIO.StringIO(c.getvalue())
because you are initialising the StringIO object at creation time, and the file pointer is positioned at the beginning of the buffer.

Get the results of dis.dis() in a string

I am trying to compare the bytecode of two things with difflib, but dis.dis() always prints it to the console. Any way to get the output in a string?
If you're using Python 3.4 or later, you can get that string by using the method Bytecode.dis():
>>> s = dis.Bytecode(lambda x: x + 1).dis()
>>> print(s)
1 0 LOAD_FAST 0 (x)
3 LOAD_CONST 1 (1)
6 BINARY_ADD
7 RETURN_VALUE
You also might want to take a look at dis.get_instructions(), which returns an iterator of named tuples, each corresponding to a bytecode instruction.
Uses StringIO to redirect stdout to a string-like object (python 2.7 solution)
import sys
import StringIO
import dis
def a():
print "Hello World"
stdout = sys.stdout # Hold onto the stdout handle
f = StringIO.StringIO()
sys.stdout = f # Assign new stdout
dis.dis(a) # Run dis.dis()
sys.stdout = stdout # Reattach stdout
print f.getvalue() # print contents

Redirect subprocess to a variable as a string [duplicate]

This question already has answers here:
Closed 11 years ago.
With the following command, it prints '640x360'
>>> command = subprocess.call(['mediainfo', '--Inform=Video;%Width%x%Height%',
'/Users/Desktop/1video.mp4'])
640x360
How would I set a variable equal to the string of the output, so I can get x='640x360'? Thank you.
If you're using 2.7, you can use subprocess.check_output():
>>> import subprocess
>>> output = subprocess.check_output(['echo', '640x360'])
>>> print output
640x360
If not:
>>> p = subprocess.Popen(['echo', '640x360'], stdout=subprocess.PIPE)
>>> p.communicate()
('640x360\n', None)
import subprocess
p = subprocess.Popen(["ls", "-al"], stdout=subprocess.PIPE)
out, err = p.communicate()
print out

Categories

Resources