如何在python中获取环境文件?

时间:2019-08-21 17:12:13

标签: python-3.7

我正在尝试使用Python来自动重启应用程序,该应用程序当前是通过Shell脚本实现的。在运行重新启动命令之前,我们需要获取一个.sh环境文件,该文件在shell脚本中使用 。 ./opt///**.sh。我正在使用paramiko和exec_command运行重新启动命令,该命令引发库丢失的错误。因此,我尝试了几种方法来在python程序中获取此环境文件,但未成功。

我尝试过的事情:

  1. stdin1,stdout1,stderr1 = ssh_client1.exec_command(“。./opt/ / / **。sh”)

  2. stdin1,stdout1,stderr1 = ssh_client1.exec_command(“源/ opt / / / **。sh”)

  3. subprocess.call(“ / opt / / / **。sh”,shell = True)

  4. os.system(“。/opt / / / **。sh”)

  5. 如果我没记错的话,我从堆栈溢出中选择了以下内容 enter code here命令= shlex.split(“ bash -c'源/opt///**.sh'”) enter code here proc = subprocess.Popen(命令,stdout = subprocess.PIPE) enter code here用于proc.stdout中的行: enter code here(键,_,值)= line.partition(“ =”) enter code here os.environ [key] =值 enter code here proc.communicate()

当我使用exec_command(“ / opt / / / start”运行应用程序重新启动命令时,如果我没有源环境文件,我仍然会遇到丢失缺少库的错误。 )

我们非常感谢您的帮助。

谢谢。

1 个答案:

答案 0 :(得分:0)

@Martin Prikryl:Execute multiple commands in Paramiko so that commands are affected by their predecessors

我爱你,男人!我正在使用paramiko向远程ssh编写py脚本,该脚本在运行应用程序重新启动命令之前会获取本地环境文件。在过去的两个星期里,我一直在挣扎,直到我读了这篇文章。它像一种魅力。谢谢!!

解决方案: 每个exec_command多次在其自己的“外壳”中执行。因此,先前的命令对以下命令的环境没有影响。

使用&&组合命令。这样,前一个命令(在我的情况下是环境文件)会对后一个命令产生影响。

stdin3,stdout3,stderr3 = ssh_client1.exec_command(“。/opt///env.sh && STOP”)