gpt4 book ai didi

Python变量条件测试失败

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

我有一个我写的 python 脚本,可以将我连接到 VPN。在此之前,它会测试我的外部 IP,并将输出记录为变量“originip”,然后它连接到我的 vpn,并再次运行测试。它显示我的 originip,然后是我的 newip,然后它运行一个条件 if 测试 origin ip 和 newip 是否相同然后说有错误。稍后我会在那里添加额外的逻辑。目前,该程序运行良好,但它始终打印“出现错误,正在重置”,而不是转到 Else 行并打印“您现在已成功连接”

我认为这里的 if 逻辑有问题:

if newip and originip == originip:
print "there was an error, resetting..."
else:
print "You are now connected successfully"

所以我已经测试了上面的内容,当我的 VPN 连接正常时,它报告新旧 IP 地址不同,然后打印“出现错误,正在重置”如果连接成功,并且显示 newip 和 originip 相同,它还会打印“出现错误,正在重置...”

我无法让它执行上述语句的 else 部分。

这是程序的整个 python 部分

#!/usr/bin/env python
import pexpect
import sys
import os
import time
import subprocess
secdelay = int(raw_input("How many seconds before resetting? "))
p = subprocess.Popen(["./checkmyip.sh"], shell=False, stdout=subprocess.PIPE)
originip = p.stdout.read()
print 'Public IP Address is', originip
child = pexpect.spawn ('./vpn.sh -arg1')
child.expect ('')
child.expect ('(?i)Enter Aut Username:')
child.sendline ('myusername')
child.expect ('(?i)Enter Auth Password:')
child.sendline ('mypassword')
print "Establishing connection..."
time.sleep(10)
p = subprocess.Popen(["./checkmyip.sh"], shell=False, stdout=subprocess.PIPE)
newip = p.stdout.read()
print "The New IP is ",newip
print "the old IP was ", originip
if newip and originip == originip:
print "there was an error, resetting..."
else:
print "You are now connected successfully"
print "sleeping for ",secdelay," seconds"
time.sleep(secdelay)
child.sendcontrol('c')
if child.isalive():
child.sendcontrol('c')
child.close()
if child.isalive():
print 'Child did not exit gracefully.'
else:
print 'Child exited gracefully.'

最后,这是我添加到“checkmyip.sh”脚本中的代码。这只是一个简单的 wget:

#!/usr/bin/env bash
wget -q -O - checkip.dyndns.org|sed -e 's/.*Current IP Address: //' -e 's/<.*$//'

所以脚本工作正常,只是这个错误检查逻辑让我感到困惑。为什么我的 if x and y == x 不起作用,当 x 和 y 都在我的 if 语句正上方的打印行中枚举不同的值时,我很困惑。

如有任何建议或帮助,我们将不胜感激。感谢阅读!

感谢大家的帮助!固定代码是这样的:

if newip and originip == originip:

改为

if newip == originip:

最佳答案

试试这个:

if newip == originip:
print "there was an error, resetting..."

关于Python变量条件测试失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14070984/

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