简体   繁体   中英

how to copy os.system('cat /var/log/dmesg') to a variable

import sys
import os

log = os.system('cat /var/log/demesg')

This code prints the file by running the shell script cat /var/log/dmesg . However, it is not copied to the log. I want to use this data somewhere else or just print the data like print log.

How can I implement this?

Simply read from the file yourself:

with open('/var/log/dmesg') as logf:
    log = logf.read()
print(log)

To read input from a child process you can either use fork (), pipe () and exec () from the os module; or use the subprocess module

As an option, take a look at IPython. Interactive Python brings a lot of ease of use tools to the table.

ipy$ log = !dmesg
ipy$ type(log)
 <3> IPython.utils.text.SList
ipy$ len(log)
 <4> 314

calls the system, and captures stdout to the variable as a String List.

Made for collaborative science, handy for general purpose Python coding too. The web based collaborative Notebook (with interactive graphing, akin to Sage notebooks) is a sweet bonus feature as well, along with the ubiquitous support for parallel computing.

http://ipython.org

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM