如何在python脚本中设置bash脚本,而不是使用单独的脚本?

2024-09-29 23:18:40 发布

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

这就是我如何运行myscript.sh中设置的bash脚本

#!/bin/bash
import subprocess
child = subprocess.Popen(['bash', '-c', '/bin/bash myscript.sh'], stdout = subprocess.PIPE)
output=child.communicate()
print(output)

myscript.sh

为什么我要这样做是因为我必须运行的bash脚本没有export命令,所以我在这里回音。代码如下。我知道echoong不会设置环境变量,但我只想回显它并获取值,以便回显而不是导出

#!/bin/bash
source ia_servers
echo $IA_SRV_cs68_64

其中,$IA\u SRV\u cs68\u 64

下面是列出变量值的ia\u servers文件 看起来像这样

IA_SRV_cs68_64="ds1 ds2 ds3 ds5 "

这就是其中的变量。因为太长,许多其他的变量被设置在它里面

从终端测试效果良好:

  • 源ia\ U服务器
  • 回音IA\ U SRV\ U cs68\ U 64

打印所需的值集

问题: 尽管myscript.sh正在运行并打印变量。我想要的是,我不想创建一个单独的文件,而是在python中编写bash脚本来回显myscript.sh中的变量

How do I accomplish it within the python rather rather than making the script file and run that.


Tags: 文件脚本bashchildoutputbinshsubprocess
1条回答
网友
1楼 · 发布于 2024-09-29 23:18:40
# i assume there is a file by name `ia_servers` with variable IA_SRV_cs68_64="ds1 ds2 ds3 ds5 "

import imp
ia_servers =imp.load_source('ia_servers', 'path to `ia_servers` file')

print ia_servers.IA_SRV_cs68_64 # this should print `ds1 ds2 ds3 ds5` 
网友
2楼 · 发布于 2024-09-29 23:18:40

这里有一种通用的方法来运行任何类型的脚本或程序,其中程序输入嵌入在Python脚本中

import subprocess
scriptres = subprocess.Popen("/bin/bash", 
                             stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE).communicate(r'''
# your bash script here
ls
pwd
source whatever
echo $SOMETHING
''')

script_stdout = scriptres[0]
script_stderr = scriptres[1]

相关问题 更多 >

    热门问题