![](/img/trans.png)
[英]How can I store the output of a command I ran using SSH from a Python script into a file?
[英]How to store the output(even errors/warning) of sql queries in a file when ran in python script?
我正在使用Python IDE在Windows上使用python脚本运行sql查询。
以下是我的示例代码,用于连接数据库并执行脚本:
#!/usr/bin/python
import MySQLdb
import sys
import cProfile
import re
import timeit
# Open database connection
db = MySQLdb.connect("localhost","bala","bala","mydb" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
import time
start_time = time.time()
// This is simple query, I was running different query,
sqlstr = "SELECT * from accounts"
cursor.execute(sqlstr)
db.commit()
print("--- %s micro seconds ---", time.time() - start_time)
print cursor.fetchall()
运行此脚本后,它将在控制台上提供输出,但是我想至少将其存储在文件或字符串变量中。 它可能会导致错误或警告,甚至也可以存储在文件/字符串中。
#!/usr/bin/python
import MySQLdb
import sys
import cProfile
import re
import timeit
file = open("filename.txt","w")
# Open database connection
db = MySQLdb.connect("localhost","bala","bala","mydb" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
import time
start_time = time.time()
// This is simple query, I was running different query,
sqlstr = "SELECT * from accounts"
try :
a = cursor.execute(sqlstr)
for i in a :
file.write(i)
db.commit()
except :
file.write(a)
print("--- %s micro seconds ---", time.time() - start_time)
print cursor.fetchall()
这可能有效! 我已经打开了一个文件,其中“文件名”是您文件的名称,并在write mod中打开了它,并在文件名为“ filename”的文件中逐行写出查询的输出。 对于错误,我使用了try和except方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.