【问题标题】:Bash to Python migrationBash 到 Python 的迁移
【发布时间】:2013-07-08 03:58:13
【问题描述】:

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

Bash 代码

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 代码中?

【问题讨论】:

    标签: python bash sqlplus


    【解决方案1】:

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

    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()         
    

    【讨论】:

    • 问题是我没有安装cx_Oracle 模块。我没有在运行python 的服务器上安装的访问权限。因此,另一种方法。
    • 与可以安装该模块的人交谈并要求他们安装。除非您至少尝试过解决问题,否则不要解决问题。
    • Ansgar ,对不起,我正在自己的时间学习这个(因为 python 默认出现在我们的服务器 unix intallation 中)。无法让系统管理员为我在服务器上安装新东西。但我很感激你花时间回答这个问题,我已经提高了你的答案:)
    猜你喜欢
    • 1970-01-01
    • 2011-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-06
    • 1970-01-01
    • 1970-01-01
    • 2013-07-01
    相关资源
    最近更新 更多