Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

An example Analysis of print output redirection of Python

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "Python's print output redirection example analysis". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Print () is most commonly used by debuggers in Python, and sys.stdout.write () is actually called when printing with print (). However, print appends a newline character (linefeed) after printing the content to the console. In the following routine, print and sys.stdout.write () are equivalent:

Sys.stdout.write ('Hello World\ n') print ('Hello World')

In Python, sys.stdin, sys.stdout and sys.stderr correspond to the standard input, standard output and standard error stream of the interpreter, respectively. When the program starts, the initial values of these objects are saved by sys.stdin, sys.__stdout__ and sys.__stderr__, which makes it easier to recover standard stream objects. As follows:

Print (sys.stdout) # print (sys.stdin) # print (sys.stderr) # print (sys.__stdout__) # print (sys.__stdin__) # print (sys.__stderr__) #

What if we want to redirect the content into the text? Let's first look at the difference between ordinary text objects and standard output objects. As follows:

Print (dir (sys.stdout)) "" ['_ CHUNK_SIZE','_ _ class__','_ _ del__','_ _ delattr__','_ _ dict__','_ _ dir__','_ _ doc__','_ enter__','_ eq__','_ exit__','_ format__','_ _ ge__','_ getattribute__' '_ _ getstate__',' _ _ gt__','_ _ hash__','_ _ init__','_ _ init_subclass__','_ _ iter__','_ _ le__','_ _ lt__','_ _ ne__','_ _ new__','_ next__','_ reduce__','_ reduce_ex__','_ _ repr__' '_ _ setattr__',' _ _ sizeof__','_ _ str__','_ _ subclasshook__','_ checkClosed','_ checkReadable','_ checkSeekable','_ checkWritable','_ finalizing', 'buffer',' close', 'closed',' detach', 'encoding',' errors', 'fileno',' flush', 'isatty',' line_buffering', 'mode',' name' 'newlines',' read', 'readable',' readline', 'readlines',' reconfigure', 'seek',' seekable', 'tell',' truncate', 'writable',' write', 'write_through',' writelines'] "with open ('redirect.txt', 'w') as f: print (f) # print (dir (f))" [' _ CHUNK_SIZE' '_ _ class__',' _ _ del__','_ _ delattr__','_ _ dict__','_ _ dir__','_ _ doc__','_ _ enter__','_ _ eq__','_ _ exit__','_ _ format__','_ ge__','_ getattribute__','_ getstate__','_ _ gt__' '_ _ hash__',' _ _ init__','_ _ init_subclass__','_ _ iter__','_ _ le__','_ _ lt__','_ _ ne__','_ _ new__','_ _ next__','_ _ reduce__','_ reduce_ex__','_ _ repr__','_ _ setattr__' '_ sizeof__',' _ _ str__','_ _ subclasshook__','_ checkClosed','_ checkReadable','_ checkSeekable','_ checkWritable','_ finalizing', 'buffer',' close', 'closed',' detach', 'encoding',' errors', 'fileno',' flush', 'isatty',' line_buffering', 'mode',' name', 'newlines' 'read',' readable', 'readline',' readlines', 'reconfigure',' seek', 'seekable',' tell', 'truncate',' writable', 'write',' write_through', 'writelines'] ""

You can see that both are file objects, and the methods contained in them are the same, such as write, read, and so on. So, if you assign a reference to a file object to sys.stdout, then print calls the write method of the file object, thus implementing the redirection. In fact, I told you about ancient times in the previous Python basic tutorials. The code is as follows:

With open ('redirect.txt', 'w') as f: sys.stdout = f print ("Hello World")

After the redirection, the print print is moved from the console to the text, as shown below:

If you print content to a file temporarily and still print it on the console, you should first save the original console reference object, and then restore the reference to sys.stdout. As follows:

_ _ console__ = sys.stdout# redirection start#... # redirection endsys.stdout = _ _ console__

The above implementation is not elegant, and the typical implementation is as follows:

# temporarily redirect standard output to a file, and then restore normal with open ('redirect.txt', 'w') as f: oldstdout = sys.stdout sys.stdout = f try: help (_ _ import__) finally: sys.stdout = oldstdoutprint ("Hello World")

Next, we introduce how the Pyhton context manager redirect_stdout implements redirection. Contextlib.redirect_stdout joins in Python 3.4. As follows:

With open ('redirect.txt',') as f: with contextlib.redirect_stdout (f): help (pow)

Of course, the inherent implementation logic of redirect_stdout is simply to save a reference to the console and then restore it. So we can implement our own redirect_stdout context manager. As follows:

@ contextlib.contextmanagerdef redirect_stdout (fileobj): oldstdout = sys.stdout sys.stdout = fileobj try: yield fileobj finally: sys.stdout = oldstdoutdef redirect4 (): with open ('redirect.txt', 'w') as f: with redirect_stdout (f): help (pow) print ("Hello World") "print output redirection example Analysis of Python" ends here. Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report