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

2024-09-30 08:21:56 发布

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

警告:对python来说非常陌生

我正在尝试连接到存储在数组${INSTANCE\u 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  

如果你能帮我找出哪里出了问题,我将不胜感激。你知道吗

干杯


Tags: instanceinimportclientaddnodejsonurl
1条回答
网友
1楼 · 发布于 2024-09-30 08:21:56

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

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

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

相关问题 更多 >

    热门问题