1

将 shell 脚本转换为 python 并尝试找到执行以下操作的最佳方法。我需要它,因为它包含我需要阅读的环境变量。

if [ -e "/etc/rc.platform" ];
then
    . "/etc/rc.platform"
fi

我已经转换了“if”,但不确定如何处理 . "/etc/rc.platform" 作为源是一个 shell 命令。到目前为止,我有以下

if os.path.isfile("/etc/rc.platform"):
    print "exists" <just to verify the if if working>
    <what goes here to replace "source /etc/rc.platform"?>

我查看了 subprocess 和 execfile 没有成功。

python 脚本需要访问 rc.platform 设置的环境变量

4

5 回答 5

3

一个有点骇人听闻的解决方案是解析env输出:

newenv = {}
for line in os.popen('. /etc/rc.platform >&/dev/null; env'):
    try:
        k,v = line.strip().split('=',1)
    except:
        continue  # bad line format, skip it
    newenv[k] = v
os.environ.update(newenv)

编辑:固定拆分参数,感谢@l4mpi

于 2013-03-07T19:05:34.803 回答
1

(这是他评论中描述的解决方案 crayzeewulf 的演示。)

如果/etc/rc.platform只包含环境变量,您可以读取它们并将它们设置为 Python 进程的环境变量。

鉴于此文件:

$ cat /etc/rc.platform
FOO=bar
BAZ=123

读取和设置环境变量:

>>> import os
>>> with open('/etc/rc.platform') as f:
...     for line in f:
...         k, v = line.split('=')
...         os.environ[k] = v.strip()
... 
>>> os.environ['FOO']
'bar'
>>> os.environ['BAZ']
'123'
于 2013-03-07T17:48:08.890 回答
0

回报的工作量太大了。打算保留一个小的 shell 脚本来获取我们需要的所有环境变量,而忘记将它们读入 python。

于 2013-03-11T23:24:30.323 回答
-1

试试这个:

if os.path.exists ("/etc/rc.platform"):
    os.system("/etc/rc.platform")
于 2013-03-07T16:25:52.733 回答
-1

由于source是内置的shell,因此您需要shell=True在调用时设置subprocess.call

>>> import os
>>> import subprocess
>>> if os.path.isfile("/etc/rc.platform"):
...     subprocess.call("source /etc/rc.platform", shell=True)

我不确定您要在这里做什么,但我仍然想提一下:/etc/rc.platform可能会导出一些 shell 函数以供rc.d. 由于这些是 shell 函数,它们将仅导出到由调用的 shell 实例subprocess.call(),如果您调用 another subprocess.call(),这些函数将不可用,因为您正在生成一个新的 shell 来调用新脚本。

于 2013-03-07T16:26:38.423 回答