How to write something into input() built-in function from code directly - python

I have a need to fill stdin from code directly when input() is waiting for filling.
Is there to do the next:
# Here suppose to be some code that will automatically fill input() below
string = input("Input something: ")
# Or here
I've heard about subprocess.Popen, but I don't understand how to use it in my case. Thank you.

This code is something:
import sys
from io import StringIO
class File(StringIO):
def __init__(self):
self._origin_out = sys.stdout
self._origin_in = sys.stdin
sys.stdout = self
sys.stdin = self
self._in_data = ''
super(File, self).__init__()
def write(self, data):
if data == 'My name is:':
self._in_data = 'Vasja\n'
else:
self._origin_out.write(data)
def readline(self, *args, **kwargs):
res = self._in_data
if res:
self._in_data = ''
return res
else:
return sys.stdin.readline(*args, **kwargs)
def __del__(self):
sys.stdout = self._origin_out
sys.stdin = self._origin_in
global_out_file = File()
a = input('My name is:')
print('Entered name is:', a)

Related

App Using Pickle On Python Crashing When Running

I Have Tried To Make A Simple Notepad App (Not Finished So That's Why "y" is incomplete)
import pickle
var1 = input("Open Last Note?(y/n)")
if var1 = "y":
if var1 = "n":
note = input("Note")
class MyClass()
def __init__(self, param):
self.param = param
def save_object(obj):
try:
with open("data.pickle", "wb") as f:
pickle.dump(obj, f, protocol=pickle.HIGHEST_PROTOCOL)
except Exception as ex:
print("Error during pickling object (Possibly unsupported):", ex)
obj = MyClass(note)
save_object(obj)
You app crash becourse here an error. Next sample is uncorrect:
if True:
if True:
#comment
You must write pass if expression of function don't have body
if True:
pass
if True:
#comment
pass
Also you can use Ellipsis:
if True:
...
#Elepsis
There are another errors in youre code:
import pickle
var1 = input("Open Last Note?(y/n)")
if var1 == "y": #need double = in compare
pass
if var1 == "n": #need == in compare
note = input("Note")
class MyClass(): #you miss colon
def __init__(self, param):
self.param = param
def save_object(obj):
try:
with open("data.pickle", "wb") as f:
pickle.dump(obj, f, protocol=pickle.HIGHEST_PROTOCOL)
except Exception as ex:
print("Error during pickling object (Possibly unsupported):", ex)
obj = MyClass(note)
save_object(obj)

Python Decorator Log file not generating

I am new to Python and learning logging technique with Decorator.
For me the below code is not generating required log file. Debugged the code, getting correct message to logger statement but the file is not generating. From Test method i am call the required function where i have implemented Decorator. Please guide where i am doing mistake.
try:
import csv
import requests
import datetime
import os
import sys
import logging
except Exception as e:
print("Some Modules are missing {}".format(e))
class Meta(type):
""" Meta class"""
def __call__(cls, *args, **kwargs):
instance = super(Meta, cls).__call__(*args, **kwargs)
return instance
def __init__(cls, name, base, attr):
super(Meta, cls).__init__(name, base, attr)
class log(object):
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
""" Wrapper Function"""
start = datetime.datetime.now() #start time
Tem = self.func(*args) #call Function
Argument = args
FunName = self.func.__name__ #get Function name
end = datetime.datetime.now() #end Time
message = """
Function : {}
Execustion Time : {}
Argument : {}
Memory : {} Bytes
Date : {}
""".format(FunName,
end-start,
Argument,
sys.getsizeof(self.func),
start
)
cwd = os.getcwd();
folder = 'Logs'
newPath = os.path.join(cwd, folder)
try:
"""Try to create a folder """
os.mkdir(newPath)
except:
"""Folder already exist """
logging.basicConfig(filename='apiRun.log'.format(newPath), level=logging.DEBUG)
logging.debug(message)
return Tem
class APIHelper(metaclass=Meta):
def __init__(self, *args, **kwargs):
pass
#log
def star_wars_characters(url):
#self.url = url
api_response = requests.get(url)
people = []
if api_response.status_code == 200:
data = api_response.json()
for d in data['results']:
character = []
character.append(d['name'])
character.append(d['height'])
character.append(d['gender'])
people.append(character)
return people
else:
return "Bad Request"
My Test Method:
import unittest
import csv
from com.Script.APIHelper import APIHelper
class TestAPI(unittest.TestCase):
def _setUp(self, file_name):
self.api = APIHelper()
with open(file_name, "w") as self.fd:
self.csvfile = csv.writer(self.fd, delimiter = ',')
self.csvfile.writerow(['Name','Height','Gender'])
def tearDown(self):
self.fd.close()
def test_responseNotEmpty(self):
file_name = 'SWAPI.csv'
self._setUp(file_name)
people = self.api.star_wars_characters("https://swapi.dev/api/people/")
assert type(people) is list
Thanks you in Advance.
Add finally
Change filename='apiRun.log' to filename='{}/apiRun.log'
try:
"""Try to create a folder """
os.mkdir(newPath)
except:
"""Folder already exist """
finally:
logging.basicConfig(filename='{}/apiRun.log'.format(newPath), level=logging.DEBUG)
logging.debug(message)
except is executed only when an exception is raised from try.
finally is always executed.

Wy can't Powershell display a string when i use stdout in Python?

It runs fine in VS Code, but in powershell it does prompt user input but without displaying the string in "stdout".
Here is the sample piece of code:
import sys
def get_int():
sys.stdout.write("Enter number(s). ")
return map(int, sys.stdin.readline().strip().split())
def get_float():
sys.stdout.write("Enter number(s). ")
return map(float, sys.stdin.readline().strip().split())
def get_list_of_int():
sys.stdout.write("Enter numbers followed by space. ")
return list(map(int, sys.stdin.readline().strip().split()))
def get_string():
sys.stdout.write("Enter string. ")
return sys.stdin.readline().strip()
a, b, c, d = get_int()
e, f, g = get_float()
arr = get_list_of_int()
str = get_string()
Why can't Powershell display a string when i use stdout in Python?
Because the stdout device interface may buffer writes to it, so either run python in unbuffered mode:
PS C:\> python -u script.py
or explicitly flush the buffer before reading stdin:
def get_int():
sys.stdout.write("Enter number(s). ")
sys.stdout.flush()
return map(int, sys.stdin.readline().strip().split())
or you can replace sys.stdout with a wrapper that does it for you:
class Unbuffered(object):
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
def writelines(self, datas):
self.stream.writelines(datas)
self.stream.flush()
def __getattr__(self, attr):
return getattr(self.stream, attr)
sys.stdout = Unbuffered(sys.stdout)
# this will now flush automatically before calling stdin.readline()
sys.stdout.write("Enter something: ")
numbers = map(int, sys.stdin.readline().strip().split())

Modify function's code in wrapper function

Is it possible to replace the actual code of a function by the function that wraps it? Here I'm trying to replace print statements with log statements:
import logging
import re
def print_to_log(func):
def wrapper_print_to_log(*args, **kwargs):
# how to do something like this?
re.sub(r'print\s*\(', 'logging.info(', **function_code**)
return func(*args, **wargs)
return wrapper_print_to_log
#print_to_log
def greet(name='bob'):
print ("Hello, %s" % name)
print ("How are you sir?")
Is it possible to replace the code or do something similar to the above?
Perhaps you can temporarily replace sys.stdout?
import logging
import re
import sys
import io
def print_to_log(func):
def wrapper_print_to_log(*args, **kwargs):
stdout = sys.stdout
b = io.StringIO()
sys.stdout = b
try:
return func(*args, **kwargs)
finally:
sys.stdout = stdout
print(b.getvalue().upper())
return wrapper_print_to_log
#print_to_log
def greet(name='bob'):
print("Hello, %s" % name)
print("How are you sir?")
greet('justin')

python Returning data from a threaded def

I have a bit of code that gets the title of a .MP3 file
def getTitle(fileName):
print "getTitle"
audio = MP3(fileName)
try:
sTitle = str(audio["TIT2"])
except KeyError:
sTitle = os.path.basename(fileName)
sTitle = replace_all(sTitle) #remove special chars
return sTitle
I would call this function with
sTitle = getTitle("SomeSong.mp3")
To solve another problem I wanted to spawn this on its own thread so I altered my call to
threadTitle = Thread(target=getTitle("SomeSong.mp3"))
threadTitle.start()
This correctly calls the function and solves my other problem, but now I can't figure out how to get the return value of sTitle from the function into Main.
I would make a new object that extends thread so that you can get anything you want out of it at any time.
from threading import Thread
class GetTitleThread(Thread):
def __init__(self, fileName):
self.sTitle = None
self.fileName = fileName
super(GetTitleThread, self).__init__()
def run(self):
print "getTitle"
audio = MP3(self.fileName)
try:
self.sTitle = str(audio["TIT2"])
except KeyError:
self.sTitle = os.path.basename(self.fileName)
self.sTitle = replace_all(self.sTitle) #remove special chars
if __name__ == '__main__':
t = GetTitleThread('SomeSong.mp3')
t.start()
t.join()
print t.sTitle
One way to do it is to use a wrapper storing the result:
def wrapper(func, args, res):
res.append(func(*args))
res = []
t = threading.Thread(
target=wrapper, args=(getTitle, ("SomeSong.mp3",), res))
t.start()
t.join()
print res[0]
This one comfortably makes any function running in a thread taking care of its return value or exception:
def threading_func(f):
"""Decorator for running a function in a thread and handling its return
value or exception"""
def start(*args, **kw):
def run():
try:
th.ret = f(*args, **kw)
except:
th.exc = sys.exc_info()
def get(timeout=None):
th.join(timeout)
if th.exc:
raise th.exc[0], th.exc[1], th.exc[2] # py2
##raise th.exc[1] #py3
return th.ret
th = threading.Thread(None, run)
th.exc = None
th.get = get
th.start()
return th
return start
Usage Examples
def f(x):
return 2.5 * x
th = threading_func(f)(4)
print("still running?:", th.is_alive())
print("result:", th.get(timeout=1.0))
#threading_func
def th_mul(a, b):
return a * b
th = th_mul("text", 2.5)
try:
print(th.get())
except TypeError:
print("exception thrown ok.")

Categories

Resources