473,804 Members | 4,223 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

redirecting stdout to mysql table

greetings,

i would like to redirect stdout/err to a mysql table and would like a)
some peer review and b) suggestions for hardening the approach for a
general purpose class. thank you very much.
import sys
import MySQLdb

class DBLogger(object ):
def __init__(self):
self.db_name = 'odb'
self.db_host = '127.0.0.1'
self.db_table = 'sftp_manager_l og'
self.db_uname = 'roo'
self.db_passwd = ''
self.db_port = 3306
self.db = None
self.cur = None
self.sql = 'INSERT INTO %s' %self.db_table + ' VALUES(null, NOW
(), %s)'
def openDb(self):
try:
self.db = MySQLdb.connect (host = self.db_host,
user = self.db_uname,
passwd = self.db_passwd,
db = self.db_name,
)

self.cur = self.db.cursor( )
return self.db, self.cur
except Exception, e:
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
print e[0], e[1]
sys.exit(1)

def closeDb(self):
self.cur.close( )
self.db.close()

def write(self, string):
s = string.strip('\ n')
if not s=='':
self.openDb()
self.cur.execut e(self.sql, (s))
self.db.commit( )
self.closeDb()
dbl = DBLogger()
sys.stdout = dbl
sys.stderr = dbl

print 'a b c '
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
thanks again for taking the time.

Nov 18 '08 #1
1 3329

n00b def openDb(self):
n00b try:
n00b self.db = MySQLdb.connect (host = self.db_host,
n00b user = self.db_uname,
n00b passwd = self.db_passwd,
n00b db = self.db_name,
n00b )
n00b>
n00b self.cur = self.db.cursor( )
n00b return self.db, self.cur
n00b except Exception, e:
n00b sys.stdout = sys.__stdout__
n00b sys.stderr = sys.__stderr__
n00b print e[0], e[1]
n00b sys.exit(1)
...
n00b def write(self, string):
n00b s = string.strip('\ n')
n00b if not s=='':
n00b self.openDb()
n00b self.cur.execut e(self.sql, (s))
n00b self.db.commit( )
n00b self.closeDb()

You don't really want to open a new database connection for every write call
do you?

--
Skip Montanaro - sk**@pobox.com - http://smontanaro.dyndns.org/
Nov 18 '08 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
12718
by: Birch | last post by:
I have a python script that uses the print function throughout, and as well uses calls to os.system() to spawn DOS commandline executables. My issue is that I redirect all of the output from this script to a file (including that which is printed by the spawned programs) via the redirect (">") function on a Win2K Command Prompt. In the captured output however, the output from the os.system() calls ALWAYS comes before the output from the...
3
3762
by: David Douard | last post by:
Hi everybody, let me explain by problem: I am working on an application which consists in a C++ dll (numeric computations) and a Python IHM (Python/Tk), which must run under Linux and win32. My problem is the C++ lib does write stuffs on its stdout, and I would like to print those messages in a Tk frame. When I run the computation, it has it's own thread. So my question is : how van I redirect the dll's stdout to something I can
3
3435
by: Laszlo Zsolt Nagy | last post by:
Hello, I have this code: s = smtplib.SMTP() s.set_debuglevel(1) s.connect(host=smtp_host) s.set_debuglevel(0) log("Connected, sending e-mail") sys.stdout.flush()
15
3127
by: Matt Burland | last post by:
I'm having a problem with redirecting the StandardOutput of a process that I use to run a DOS program in my application. The problem is that I when I start my process (which I do in a separate thread) I can't read anything from the stdout before the process actually finishes. If I do something like this: Process myProcess = new Process(myStartInfo) // this gets shown straight away MessageBox.Show("Process Started"); string s =...
9
1771
by: Fuzzyman | last post by:
Hello, I'm trying to redirect standard out in a single namespace. I can replace sys.stdout with a custom object - but that affects all namespaces. There will be code running simultaneously that could import sys afterwards - so I don't want to make the change in the sys module.
8
5791
by: Morpheus | last post by:
I am trying to test a function that outputs text to the standard output, presumably using a cout call. I do not have access to the source, but need to test the output. Is this possible? I can technically create an executable that calls the function and then using a command prompt call the exexutable using the > output.txt redirector but I would prefer to do everything within the application itself. Is there a way for force an output...
1
2598
by: pp4175 | last post by:
Hello Everyone, I am currently working on writing a GUI wrapper for a Menu driven DOS Program. What I was looking on doing is redirecting stdout/stdin to a stream and read/write similar to a file. My issue is that I try to read from the stdout stream and never get anything only if the program has exited. Is there a way of reading the redirected stdout from a DOS program in say real time? I have tried the async (BeginOutputReadLine) and...
5
2615
by: =?gb2312?B?yMvR1MLkyNXKx8zs0cSjrM37vKvM7NHEsru8+7z | last post by:
I wanna print the log to both the screen and file, so I simulatered a 'tee' class Tee(file): def __init__(self, name, mode): file.__init__(self, name, mode) self.stdout = sys.stdout sys.stdout = self
4
9744
by: ElderGeek | last post by:
Hi, all. I am coding in C on Linux, and using an external library provided by others. This library generates a batch of error/warning messages to stdout, which I do not want to see. Before each function call to the external library, I can insert the following: freopen("/dev/null", "w", stdout); However, after the function call I cannot figure out how to reroute stdout to the console. I tried early in the program defining: FILE...
0
9706
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9579
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10577
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10320
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10077
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7620
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6853
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5651
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2991
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.