gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:03:10 24 4
gpt4 key购买 nike

警告:对 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com