How to get the last, by the code, printed text Python - string

Let's say my code looks like:
print('Hello World')
result:
>>>Hello World
How can I retrieve what has been printed and put it in a string or in a list of strings if it's more than one print (for example by saying from where to where it should get them)

You can overload the print function, and do something along these lines:
import sys
last_out = ''
def print(message):
global last_out
last_out = message
sys.stdout.write(message+'\n')
print('derp')
print(last_out)
Output:
derp
derp
You could also save the message in an array, and retrieve the last x amount of strings for example

Related

Using the file name as the parameter of the function and removing one list from another

I have written a code but probably the function part is not correct. I should make a function of the file name and then Return back to it.
Secondly, the has to be another function that removes the elements of text2_words from text1_words.
I have the code but I do not have a function for removing the text2_words list from text1_words and my function for the filename is not correct because I can not return to it.
Expecting result:
Insert name of the file:text.txt
Number of words in the text: 96
Number of unique words: 42
Hitta
din
nyhet
Stoff
nyheter
runt
.
.
.
Code:
import re
def common_words(filename, text2="vanligaord.txt"):
text1=0
infile_1= open("text.txt", "r")
filename=text1
text1=input('Insert name of the file:')
text1=infile_1.read()
for punctuation in '!,?,.,-':
text1=text1.replace(punctuation, " ")
text1_words=text1.split()
print('Number of words in the text:', len(text1_words))
infile_2= open("vanligaord.txt", "r",encoding='latin_1')
text2= infile_2.read()
text2_words=text2.split('\n')
unique_words=[]
for word in text1_words:
if word not in text2_words:
unique_words.append(word)
print('Number of unique words:', len(unique_words))
print ('\n'.join(unique_words))
Expected Output Screenshot:

F-Strings and writing function output to file in python3

I want to simply write output of my function to a file, but it returns None. The function itself works perfectly fine and just print statements.
#I have reproduced the issue with minimum LOC:
def syl(txt):
for x in text:
print(x)
text = 'example text'
file = 'example'
with open(F"""SYL_{file}""",'a+',encoding='UTF8') as f:
f.write(F'''{syl(text)}''')
content = f.readlines()
print(content)
Prints '[]'
F'''{syl(text)}'''" #it returns only 'None'.
I have tried also:
with open(F"""SYL_{file}""",'a+',encoding='UTF8') as f:
f.write(syl(text)) #str(syl(text)) Doesnt work too, writelines() also changes nothing.
Make sure that the function actually returns something (a function with no explicit returns, returns None), print statements simply appear on the console and don't get processed as the output of the function. Try this, using a list comprehension:
def syl(txt):
# returns a list of the chars in txt
return [x for x in txt]
Now for the writing part. Well, it turns out that you don't actually need to call the function (what did you intend to do with the function?), just write the text:
f.write(text)

What did I do wrong

import sys
super_heroes = {'Iron Man' : 'Tony Stark',
'Superman' : 'Clark Kent',
'Batman' : 'Bruce Wayne',
}
print ('Who is your favorite Superhero?')
name = sys.stdin.readline()
print ('Do you know that his real name is', super_heroes.get(name))
I'm doing a simple code here that should read an input in a dictionary and print it out after a string of letters, but when ran it prints out
"
Who is your favorite Superhero?
Iron Man
Do you know that his real name is None
"
Even Though the input is in my dictionary.
Your input is having a newline at the end of the line.
I have tried it online REPL. Check it
try following to resolve it.
name = sys.stdin.readline().strip()
After stripping Check here
sys.stdin.readline() returns the input value including the newline character, which is not what you expect. You should replace sys.stdin.readline() with input() or raw_input(), which are really more pythonic ways to get input values from the user, without including the newline character.
raw_input() is preferable to ensure that the returned value is of string type.
To go a little bit further, you can then add a test if name in super_heroes: to perform specific actions when the favorite superhero name is not in your dictionary (instead of printing None). Here is an example:
super_heroes = {'Iron Man' : 'Tony Stark',
'Superman' : 'Clark Kent',
'Batman' : 'Bruce Wayne',
}
print ('Who is your favorite Superhero?')
name = raw_input()
if name in super_heroes:
print ('Do you know that his real name is', super_heroes[name], '?')
else:
print ('I do not know this superhero...')
sys.std.readline() appends a line break at the end of user input you may want to replace it before getting your Super Hero:
name = name.replace('\n','')

How to store the print of a variable as string in Python?

Suppose I have a variable that is not a string, however, when I print it out it gives a string. For simplicities sake and for giving an example say that the variable is
message = "Hello Python world!"
Although, this is a string (Suppose it is not)
I would like to store a new variable A as the print statment of this message i.e.
A=print(message)
When I code A on the other line or print(A) it does not give me any outcome.
IN: A
Out:
IN: print(A)
Out: None
Can someone help me figure this out?
I'm guessing you're looking for something like this:
var = 123
A = str(var) # A is now '123'
The print() function doesn't return anything; it simply prints to the standard output stream. Internally, though, it converts non-string arguments to strings, as in the example code above.

using a list from subprocess output

I use subprocess and python3 in the following script:
import subprocess
proc = subprocess.Popen("fail2ban-client -d".split(' '), stdout=subprocess.PIPE)
out, err = proc.communicate()
out.decode('ascii')
print(out)
The output is the following:
['set', 'syslogsocket', 'auto']
['set', 'loglevel', 'INFO']
['set', 'logtarget', '/var/log/fail2ban.log']
['set', 'dbfile', '/var/lib/fail2ban/fail2ban.sqlite3']
['set', 'dbpurgeage', 86400]
...
My issue is all this output is not a list. This is just a really big string with new line.
I have tried to convert each line to a list with this command:
eval(out.decode('ascii').split('\n')[0])
But I don't think this is the good way.
So my question is how can I convert a string (which looks like a list) to a list.
Though people generally are afraid of using eval, it is the way to go if you need to convert text literals into data. Instead of splitting up your (potentially long) string, you can simply read off the first line like so:
import io
f = io.StringIO(out.decode('ascii'))
first_list = eval(f.readline())
second_list = eval(f.readline())

Resources