-1

I'm trying to use a variable defined in one function in a different function. I know I have to use Global var but I'm still not getting the output I was expecting.

def proxycall():
    global ip
    global port
    ip = "192.168.0.1"
    port = "8080"


def web1():
    class YWebPage():
        def something():
            var = 1
        def somethingelse():
            varr = 2
    class Browser():
        def someting():
            varrr = 3
        def sometingelse():
            varrrr = 4

    print (ip)
    print (port)

web1()

This minimal version of my program is giving the traceback - NameError: global name 'ip' is not defined.


I see the problem with the minimal version now, thanks for pointing it out. However I don't think thats my issue now because I call proxycall() in the full version below, any ideas?

import sys
from PyQt4 import QtCore, QtGui, QtWebKit
from PyQt4.QtWebKit import QWebSettings
from PyQt4.QtNetwork import QNetworkAccessManager
from PyQt4.QtNetwork import *
import re
import requests

UA_STRING = """Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36""" # String for User-Agent
#vidurl = "http://www.youtube.com/watch?v=hqDT6G5_1tQ" # 94 views
vidurl = "http://httpbin.org"


def proxycall():
            global ip
            global port
                # Proxy Stuff
            count = 0
            while (count < 5):

                 #Call mashape proxy API and setup
              try:
                 headers = {'X-Mashape-Authorization':'xxxxxxxxxxxxx'}
                 p = requests.get('https://webknox-proxies.p.mashape.com/proxies/new?maxResponseTime=5', headers=headers, timeout=5.000)
                 prox = p.text
                 ip = prox.split(":")[1]   #split response string
                 port = prox.split(":")[2]
                 ip = re.sub('["}]', '', ip)   #sanitize output
                 port = re.sub('["}]', '', port)
                 proxy = str(ip) + ':' + str(port) #reformat proxy for Requests
                 print ('Retrieved proxy ' + str(proxy))
                 proxies = {"http": proxy}
                 print ('Configured proxy')
              except:
                 print('Mashape API error, FAIL')

                 #Get real IP address
              try:
                 r = requests.get('http://httpbin.org/ip', timeout=5.000)
                 s = r.text
                 realip = re.findall( r'[0-9]+(?:\.[0-9]+){3}', s )
                 print ('Real IP address is ' + str(realip))
              except:
                 print ("Connection Error (IP), FAIL")

                 #Test proxy
              try:
                 x = requests.get('http://bot.whatismyipaddress.com/', proxies=proxies, timeout=5.000)
                 y = x.text
                 proxyip = re.findall( r'[0-9]+(?:\.[0-9]+){3}', y )
                 print ('Masked IP address is ' + str(proxyip))
                 if proxyip != realip:
                    print ('Proxy test OK')
                    count = 100
                 else:
                    print ('Proxy test FAIL, GET new proxy...')  
              except:
                 print ("Connection Error (Proxy), FAIL")

def web1(parent):

    class YWebPage(QtWebKit.QWebPage):
        def __init__(self):
            super(QtWebKit.QWebPage, self).__init__()

        def userAgentForUrl(self, url):
            return UA_STRING


    class Browser(QtGui.QMainWindow): # "Browser" window


        def __init__(self, parent):
            QtGui.QMainWindow.__init__(self, parent)
            self.resize(800,600) # Viewport size
            self.centralwidget = QtGui.QWidget(self)
            self.html = QtWebKit.QWebView()


        def browse(self):
            self.webView = QtWebKit.QWebView()
            self.yPage = YWebPage()
            self.webView.setPage(self.yPage)
            self.webView.load(QtCore.QUrl(vidurl)) # Video URL
            self.webView.settings().setAttribute(QtWebKit.QWebSettings.PluginsEnabled,True) # Enables flash player
            self.webView.settings().setAttribute(QtWebKit.QWebSettings.AutoLoadImages, False) # No images for speed
            QWebSettings.clearMemoryCaches ()
            self.webView.show()
            proxycall()


    x = Browser(parent)
    QNetworkProxy.setApplicationProxy(QNetworkProxy(QNetworkProxy.HttpProxy, ip, port))
    x.browse()
4

5 回答 5

3

您根本没有调用proxycall(),因此从未设置变量。

先调用它,然后调用web1()

proxycall()
web1()

名称不会仅仅因为您将它们标记为global函数而突然出现;Python 名称需要赋值(绑定)才能实现。

于 2013-08-06T13:51:42.057 回答
1

您需要先调用 proxycall() 才能ip全局访问:

proxycall()
web1()
于 2013-08-06T13:51:38.213 回答
0

Your updated code has the same problem as the original code. You are using ip in this statement:

QNetworkProxy.setApplicationProxy(QNetworkProxy(QNetworkProxy.HttpProxy, ip, port))

...but you don't call proxycall until you call x.browse() in the statement after that.

于 2013-08-06T14:49:10.447 回答
0

您需要调用proxycall()初始化ip

proxycall()
web1()
于 2013-08-06T13:52:02.957 回答
0

您需要在使用它们之前进行ip初始化/定义。port打电话proxycall()然后web1()

 def proxycall():
        global ip
        global port
        ip = "192.168.0.1"
        port = "8080"


    def web1():
        class YWebPage():
            def something():
                var = 1
            def somethingelse():
                varr = 2
        class Browser():
            def someting():
                varrr = 3
            def sometingelse():
                varrrr = 4

        print (ip)
        print (port)

    proxycall()
    web1()

答案:192.168.0.1 8080

于 2013-08-06T13:55:12.883 回答