python - 在 bash for 循环中组合 python 脚本时出错

标签 python bash

警告:对 python 非常陌生

我正在尝试连接到存储在数组 ${INSTANCE_IPS[@]} 中的一系列 IP 地址。我正在尝试使用 for 循环来使用 python 脚本为数组中的每个 IP 地址调用 API。

但是,当尝试运行以下脚本时,出现错误:

Traceback (most recent call last):
File "<stdin>", line 12, in <module>
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
Traceback (most recent call last):
File "<stdin>", line 12, in <module>
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'

我确信我可以在 python 中做一个 for 循环,但我还没有学会,目前只需要让它工作。如果我只使用阵列中的一个 IP 地址,它运行良好。

for instance in ${INSTANCE_IPS[@]}
do
  echo "Connecting to $instance"

  /usr/bin/python << END_OF_PYTHON

  import requests
  import json
  import sys
  import socket
  import fnmatch
  import os

  ipaddress = os.getenv('instance')
  print ipaddress

  port = ':80'
  updatedipaddress = ipaddress +port
  print 'updated ip address is ' + updatedipaddress

  add_node = updatedipaddress

  print 'add_node is ' + add_node

  url = 'https://' + os.getenv('instance') + ':9070/api/tm/1.0/config/active/pools/' + 'aol_http'
  print 'url is ' + url
  jsontype = {'content-type': 'application/json'}
  client = requests.Session()
  client.auth = ('username', 'password')
  client.verify = 0

  response = client.get(url)
  print response
  pools = json.loads(response.content)
  nodes = pools['properties']['basic']['nodes']

  data = nodes
  data.append(unicode(add_node))

  client.put(url,json.dumps(pools), headers=jsontype)
  END_OF_PYTHON
done  

如能帮助我找出问题所在,我们将不胜感激。

干杯

最佳答案

bash 变量 instance 不会传递给子进程。您必须在启动 python 代码之前导出它。这可以在有关 ipaddress + port 的错误消息中看到,因为 ipdaddress 是 NoneType,这意味着 os.getenv() 不起作用。

for instance in ${INSTANCE_IPS[@]}
do
  echo "Connecting to $instance"
  export instance

  /usr/bin/python << END_OF_PYTHON
   [...]

关于python - 在 bash for 循环中组合 python 脚本时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23454373/

相关文章:

bash - 在命令替换中使用引号

python - 查询机器主机名

Python:比较列表中的元素并打印具有最大匹配计数的元素

python - 使用正则表达式查找并替换每个匹配的任意数量的元素

python - 在使用 read_fwf() 读取的 Pandas 数据框中查找虚假数据

bash - 如何将输入通过管道传递给 Bash while 循环并在循环结束后保留​​变量

bash - 用-ldflags传递给Go编译器的字符串中的Shell变量不会扩展

Python 从公共(public)目录导入

Python包和模块版本管理

bash - 使用 bash 脚本压缩带有子文件夹和另一个目标文件夹的 .mp4