在Python中执行BASH命令——在相同的过程中

2024-09-27 20:15:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要先执行命令. /home/db2v95/sqllib/db2profile,然后才能在Python 2.6中import ibm_db_dbi

在输入Python之前执行它:

baldurb@gigur:~$ . /home/db2v95/sqllib/db2profile
baldurb@gigur:~$ python
Python 2.6.4 (r264:75706, Dec  7 2009, 18:45:15) 
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import ibm_db_dbi
>>> 

但是在Python中使用os.system(". /home/db2v95/sqllib/db2profile")subprocess.Popen([". /home/db2v95/sqllib/db2profile"])执行它会导致错误。我做错什么了?

编辑:这是我收到的错误:

> Traceback (most recent call last):  
> File "<file>.py", line 8, in
> <module>
>     subprocess.Popen([". /home/db2v95/sqllib/db2profile"])  
> File
> "/usr/lib/python2.6/subprocess.py",
> line 621, in __init__
>     errread, errwrite)   File "/usr/lib/python2.6/subprocess.py",
> line 1126, in _execute_child
>     raise child_exception OSError: [Errno 2] No such file or directory

Tags: inpyimporthomedblineibmfile
3条回答

您正在调用“.”shell命令。此命令表示“在当前进程中执行此外壳文件”。不能在Python进程中执行shell文件,因为Python不是shell脚本解释器。

/home/b2v95/sqllib/db2profile可能设置了一些shell环境变量。如果您使用system()函数读取它,那么变量将只在执行的shell中更改,并且在调用该shell(您的脚本)的进程中不可见。

您只能在启动python脚本之前加载此文件–您可以创建一个shell包装脚本,它将执行. /home/b2v95/sqllib/db2profile并执行python脚本。

另一种方法是查看db2profile包含什么。如果这只是NAME=value行,那么可以在python脚本中解析它,并用获得的数据更新os.environ。如果脚本做了更多的事情(比如调用其他东西来获取值),那么可以在Python中重新实现整个脚本。

更新一个想法:将脚本读入python,在脚本将env命令写入同一个shell并读取输出后,将其管道化(使用Popen)到shell。这样就可以得到shell中定义的所有变量。现在你可以读取变量了。

像这样的:

shell = subprocess.Popen(["sh"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
script = open("/home/db2v95/sqllib/db2profile", "r").read()
shell.stdin.write(script + "\n")
shell.stdin.write("env\n")
shell.stdin.close()
for line in shell.stdout:
    name, value = line.strip().split("=", 1)
    os.environ[name] = value

你需要做的是:

subprocess.Popen(['.', '/home/db2v95/sqllib/db2profile'], shell=True)

不确定您在使用什么操作系统和使用什么DB2版本。较新的版本(至少9.5及更高版本,不确定是9.0还是9.1)通过将db2clp设置为**$$**来工作。由于DB2通常是LUW,所以它也可以在linux/unix下工作。但是,在AIX下,我需要运行profile脚本来连接到正确的DB实例。对那个脚本的功能还没有做太多的检查。

相关问题 更多 >

    热门问题