Ice*_*ack 4 python db2 bash subprocess
我需要在Python 2.6 . /home/db2v95/sqllib/db2profile之前执行命令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
>>>
Run Code Online (Sandbox Code Playgroud)
但使用执行它在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
Run Code Online (Sandbox Code Playgroud)
Jac*_*zny 10
你打电话给'.' shell命令.此命令表示"在当前进程中执行此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,将它(使用Popen)传递给shell,然后将脚本写入env命令发送到同一个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
Run Code Online (Sandbox Code Playgroud)
Fel*_*lix -1
也许os.popen是您正在寻找的(更好的是,其中一种popen[2-4]变体)?例子:
import os
p = os.popen(". /home/b2v95/sqllib/db2profile")
p.close() # this will wait for the command to finish
import ibm_db_dbi
Run Code Online (Sandbox Code Playgroud)
编辑:我看到你的错误说No such file or directory。尝试不带点运行它,如下所示:
os.popen("/home/b2v95/sqllib/db2profile")
Run Code Online (Sandbox Code Playgroud)
如果这不起作用,则可能与您的环境有关。也许你正在运行被监禁/chroot 的 Python?