1

我正在将我的以下 bash 脚本迁移到 python

重击代码

sqlplus -S User/psw@inst << EOF
whenever sqlerror exit sql.sqlcode;
set echo off 
set heading off
prompt *****************************
prompt *** Running Script 1***
@/my/location/Script1
prompt *****************************
prompt *** Running Script 2***
@/my/location/Script2
exit;
EOF

Python代码

(username, password, host) = ("user","psw","isntance") 
conn_string = " %s/%s@%s "% (username,password,host)
#for script1 
session = Popen(['sqlplus','-S', conn_string], stdin=PIPE, stdout=PIPE, stderr=PIPE)
sql_file = '%s/%s' % ('/my/folder', 'Script1.sql')
with open(sql_file) as f:
    stdout, stderr = session.communicate(f.read())
print stdout
print stderr

#for script2 
session = Popen(['sqlplus','-S', conn_string], stdin=PIPE, stdout=PIPE, stderr=PIPE)
sql_file = '%s/%s' % ('/my/folder', 'Script2.sql')
with open(sql_file) as f:
    stdout, stderr = session.communicate(f.read())
print stdout
print stderr

我有两个问题,

1)有没有办法在不打开另一个实例的情况下运行两个脚本Popen 2)如何 prompt在代码中实现功能python

4

1 回答 1

3

在 Python 中,您不应该为数据库连接而掏腰包。请改用适当的数据库模块,在本例中为cx_Oracle。Oracle 甚至对此有教程。从那里引用简单的查询示例:

import cx_Oracle

con = cx_Oracle.connect('pythonhol/welcome@127.0.0.1/orcl')

cur = con.cursor()
cur.execute('select * from departments order by department_id')
for result in cur:
    print result

cur.close()
con.close()         
于 2013-07-08T07:59:10.857 回答