【发布时间】:2015-05-27 07:34:42
【问题描述】:
我正在编写一个包装 python 脚本,在运行其他一些工具之前需要 source ./config。排除我的脚本提供的额外功能,它基本上是这样做的:
$ source ./config
$ ./a-tool.sh --args
$ ./another-tool.py --arg1 --arg2
翻译成python,我可以做一些事情来调用这两个脚本:
subprocess.call(['./a-tool.sh', '--args'])
subprocess.call(['./another-tool.py', '--arg1', '--arg2'])
但我无法弄清楚如何首先使用工具的修改环境source。我读过Emulating Bash 'source' in Python,但它建议一些黑客修改运行脚本的环境,这不是我想要的。
编辑:
澄清一下,我的脚本目前是一个 bash 脚本,它执行一系列检查、解析一些参数,并根据结果运行一个或多个如上所述的工具。 source 行并不总是需要,并且并不总是相同的。但是,使用时,以下所有工具都需要在同一环境中运行(即bash进程)。在 bash 中,这很容易。但是,我想用 python 重写脚本,因为其他一些功能对我来说更容易在 python 中编写和维护。它纯粹是基于偏好的语言选择,与实际功能无关。根据@abarnert 的回答,我想我可以做类似的事情
subprocess.call(['source', '.config', ';', './a-tool.sh', ...])
这看起来并不容易调试,所以我更喜欢这样的东西:
bash = subprocess.run('bash')
bash.execute('source ./config')
bash.execute('a-tool.sh --args')
有没有办法在python中做到这一点?
【问题讨论】:
-
有没有想过只写一个 bash 脚本然后执行你的 python 脚本?
-
是的,这就是我开始的地方。但是还有很多其他的东西可以让完全用 python 编写更容易。例如。
source仅在特定条件下实际运行。如果我找不到答案,我会将整个脚本留在 bash 中,但它很乱!