Pulling Query String from URL - python

I'm trying to pull the query string from a url typed in by the user which would be turned into an interger, so http://127.0.0.1:8000/?1653. When i try to do this python gives me the error,
File "C:\Users...\Documents\webserver\server.py", line 26, in do_GET
int(URIextra) ValueError: invalid literal for int() with base 10: ''
I don't know what i'm doing wrong here, any help would be much appreciated.
import http.server, socketserver, os
from urllib.parse import urlparse
from shutil import copyfile
dirs = []
PORT = 8000
URIextra = ""
class CustomHandler(http.server.SimpleHTTPRequestHandler):
def __init__(self, req, client_addr, server):
http.server.SimpleHTTPRequestHandler.__init__(self, req, client_addr, server)
def do_GET(self):
o = urlparse(self.path)
URIextra = str(o[4])
http.server.SimpleHTTPRequestHandler.do_GET(self)
print(URIextra)
dirs = os.listdir()
f = open("index.txt", "w")
f.write(os.listdir())
f.close()
int(URIextra)
copyfile(dirs[URIextra], "CurrentFile.mp3")
class MyTCPServer(socketserver.ThreadingTCPServer):
allow_reuse_address = True
os.chdir(os.getcwd() + "/web")
httpd = MyTCPServer(('localhost', PORT), CustomHandler)
httpd.allow_reuse_address = True
print("Serving at port", PORT)
httpd.serve_forever()

You are using URIExtra as a string:
URIextra = str(o[4])
you should use this:
URIextra = int(o[4])

I was able to change my code to work more efficiently, don't have my PC with me right now, will post it here in a bit

Related

How to import a variable from a Pytest funtion to another Python script file?

I have the below Pytest script Webtest.py where my url to be tested is defined.
from seleniumwire import webdriver
import pytest
from selenium.webdriver.chrome.options import Options
class Test_main():
#pytest.fixture()
def test_setup(self):
# initiating browser
chrome_options = Options()
chrome_options.add_argument('--start-maximized')
chrome_options.add_argument('--headless')
self.driver = webdriver.Chrome(executable_path=r"drivers/chromedriver v86/chromedriver.exe",options=chrome_options)
yield
self.driver.close()
self.driver.quit()
print("Test Completed")
def test_case01(self,test_setup):
self.url='lifesciences.cactusglobal.com'
self.driver.get(self.url)
title=self.driver.title
print(title)
I want to use the self.url value from the above script to be used in another python script SSL_trial.py. I tried it like below, but was showing error even before execution.
from OpenSSL import SSL
from cryptography import x509
from cryptography.x509.oid import NameOID
import idna
from Test_Website_Security import Test_main #imported the file which is saved in the same folder
url_here= Test_main.test_case02().url #I tried to call the variable here
from socket import socket
from collections import namedtuple
HostInfo = namedtuple(field_names='cert hostname peername', typename='HostInfo')
HOSTS = [
(url_here, 443)
]
def verify_cert(cert, hostname):
cert.has_expired()
def get_certificate(hostname, port):
hostname_idna = idna.encode(hostname)
sock = socket()
sock.connect((hostname, port))
peername = sock.getpeername()
ctx = SSL.Context(SSL.SSLv23_METHOD)
ctx.check_hostname = False
ctx.verify_mode = SSL.VERIFY_NONE
sock_ssl = SSL.Connection(ctx, sock)
sock_ssl.set_connect_state()
sock_ssl.set_tlsext_host_name(hostname_idna)
sock_ssl.do_handshake()
cert = sock_ssl.get_peer_certificate()
crypto_cert = cert.to_cryptography()
sock_ssl.close()
sock.close()
return HostInfo(cert=crypto_cert, peername=peername, hostname=hostname)
def get_alt_names(cert):
try:
ext = cert.extensions.get_extension_for_class(x509.SubjectAlternativeName)
return ext.value.get_values_for_type(x509.DNSName)
except x509.ExtensionNotFound:
return None
def get_common_name(cert):
try:
names = cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)
return names[0].value
except x509.ExtensionNotFound:
return None
def get_issuer(cert):
try:
names = cert.issuer.get_attributes_for_oid(NameOID.COMMON_NAME)
return names[0].value
except x509.ExtensionNotFound:
return None
def print_basic_info(hostinfo):
s = '''» {hostname} « … {peername}
\tcommonName: {commonname}
\tSAN: {SAN}
\tissuer: {issuer}
\tnotBefore: {notbefore}
\tnotAfter: {notafter}
'''.format(
hostname=hostinfo.hostname,
peername=hostinfo.peername,
commonname=get_common_name(hostinfo.cert),
SAN=get_alt_names(hostinfo.cert),
issuer=get_issuer(hostinfo.cert),
notbefore=hostinfo.cert.not_valid_before,
notafter=hostinfo.cert.not_valid_after
)
print(s)
print(type(s))
xyz=list(s.split("\t"))
print(xyz)
print(len(xyz))
print(xyz[5])
print(xyz[4])
def check_it_out(hostname, port):
hostinfo = get_certificate(hostname, port)
print_basic_info(hostinfo)
import concurrent.futures
if __name__ == '__main__':
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as e:
for hostinfo in e.map(lambda x: get_certificate(x[0], x[1]), HOSTS):
print_basic_info(hostinfo)
I am not sure how to do it. I know its quite basic but any help is much appreciated.
if test_case01 somehow can retun self.url then probaly you can try the below solution :-
let's say A.py looks something like this :-
def test_case01():
url = 'lifesciences.cactusglobal.com'
return url
and if you want to use url from test_case01 into B.py :-
you can probably do something like this :
from A import *
var = test_case01()
print(var)

WaitForSingleObject not working - invalid handle

I'm currently righting a code for client that can download files from a cloud. The client downloads the file temporarily and when the file is closed (terminated) it gets sent back to the cloud.
Here is the full code:
import socket
import os
from OpenFile import *
from Registry_Change import *
import win32con
import win32api
import win32event
from win32com.shell import shellcon
from win32com.shell.shell import ShellExecuteEx
class Application(object):
def __init__(self):
"""
:param request: the request of the file to receive from server
"""
# initiates request (clicked file path)
self.request = sys.argv[SECOND]
reg = Read_Registry()
ip, port = reg.get_ip_port()
self.ip = ip
self.port = port
# initiates socket
try:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect((self.ip, self.port))
# sends the request to the server
Application.send_request_to_server(self.sock, "DOWNLOAD_FILE " + self.request)
format = Application.read_server_response(self.sock).decode()
self.path_file = self.download(format)
self.start_file_and_wait()
self.sock.close()
except Exception as msg:
print(win32api.GetLastError())
print("connection error:", msg)
#staticmethod
def valid_file(path):
"""
checks if the path is a file that exists
"""
if os.path.isfile(path):
return True
return False
#staticmethod
def delete_file(file_path):
"""
deletes file
"""
os.remove(file_path)
#staticmethod
def read_server_response(server_socket_choice):
"""
reads the length and according to that, it reads the rest
of the message
"""
try:
length_of_message = server_socket_choice.recv(BYTE).decode()
if length_of_message.isdigit():
return server_socket_choice.recv(int(length_of_message))
except Exception as msg:
print("at read_server_response:", msg)
return SERVER_FELL
#staticmethod
def send_request_to_server(server_socket, request):
"""
Send the request to the server.
First the length of the request (2 digits), then the request itself
Example: '04EXIT'
Example: '12DIR c:\cyber'
"""
server_socket. \
send((str(len(request)).zfill(MSG_FILL) + request).encode())
def download(self, format):
"""
saves the given chunks to a file in the client
"""
try:
file = Application.new_format_path(self.request, format)
new_location = Application.make_new_file_path(TEMPORARY_FILES, file)
# check if the file is valid
check_len = self.sock.recv(BYTE).decode()
check = self.sock.recv(int(check_len))
if check != FILE_DOESNT_EXIST:
client_file = open(new_location, 'wb')
# write what we took out
client_file.write(check)
done = False
while not done:
byte_message_len = self.sock.recv(BYTE)
length = byte_message_len.decode()
if length.isdigit():
real_len = int(length)
data = self.sock.recv(real_len)
if data == FILE_END:
done = True
else:
client_file.write(data)
client_file.close()
return new_location
else:
return 'nothing'
except Exception as msg:
print("at download:", msg)
def upload(self, file_path):
"""
Sends a file from the server to the client
"""
if Application.valid_file(file_path):
client_file = open(file_path, 'rb')
content = client_file.read(BYTE_NUMBER)
while content != b'':
Application.send_binary_response_to_server(content, self.sock)
content = client_file.read(BYTE_NUMBER)
client_file.close()
Application.send_binary_response_to_server(FILE_END, self.sock)
Application.delete_file(file_path)
Application.make_imaginary_file(file_path)
return Application.read_server_response(self.my_socket)
else:
Application.send_response_to_server(FILE_DOESNT_EXIST, self.sock)
return FILE_DOESNT_EXIST
#staticmethod
def make_new_file_path(new_path, folder):
"""
:param new_path: new path of file to merge
:return: the new path
"""
comp = folder.split("\\")
return new_path + "\\" + comp[END]
#staticmethod
def new_format_path(path, format):
"""
:param format: the new format
:return: the same path but with new format
"""
path_format = path.split('.')
path_format[SECOND] = format
return ".".join(path_format)
def start_file_and_wait(self):
"""
:param fname: the file path - temporary
:return: opens and continues when closed
"""
rc = ShellExecuteEx(
fMask=shellcon.SEE_MASK_NOCLOSEPROCESS,
nShow=win32con.SW_SHOW,
lpFile=self.path_file)
hproc = rc['hProcess']
win32event.WaitForSingleObject(hproc, win32event.INFINITE)
win32api.CloseHandle(hproc)
app = Application()
Now, the win32event.WaitForSingleObject(hproc, win32event.INFINITE) command does not work, and returns the error: "(6, 'WaitForSingleObject', 'The handle is invalid.')".
When I tried to use the start_file_and_wait(self) function in a separate file, it worked:
def start_file_wait(fname):
import win32con
import win32api
import win32event
from win32com.shell import shellcon
from win32com.shell.shell import ShellExecuteEx
rc = ShellExecuteEx(
fMask=shellcon.SEE_MASK_NOCLOSEPROCESS,
nShow=win32con.SW_SHOW,
lpFile=fname)
hproc = rc['hProcess']
win32event.WaitForSingleObject(hproc, win32event.INFINITE)
win32api.CloseHandle(hproc)
def main():
start_file_wait("E:\\12\\alice-chapter-1.txt")
print("hi")
if __name__ == '__main__':
main()
I don't know how to fix it. can someone help me?
Thanks!
It doesn't work on files that aren't text files
As you said, You did not specify a suitable verb for ShellExecuteEx, according to the parameter:
lpVerb :
... This parameter can be NULL, in which case the default verb is
used if available. If not, the "open" verb is used. If neither verb is
available, the system uses the first verb listed in the registry.
It may fail and return an invalid hProcess handle if it cannot find the associated application to open the file. You should specify a valid verb according to the file you open. Or specify the executable file of the app corresponding to the file as lpFile, and specify the file as lpParameters.
You could refer to the following document:
Launching Applications

how to get proxy ip and port from text file

how to get proxy ip and port from text file
Code :
import re , urllib , urllib2 , socks , socket
proxys = open('IPs.txt', 'r')
links = open('URs.txt', 'r')
#----
P = proxys.readlines()
E = links.readlines()
#----
nm = 0
#----
PROXY = P[nm]
#----
for links in E :
Post = 'id='+ links
cj = CookieJar()
#----
IP,PORT = PROXY.split(":")
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, IP, PORT)
socket.socket = socks.socksocket
#----
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
request = urllib2.Request('https://google.com/', Post)
# ----------------- ++
nm+=1
PROXY = P[nm]
# ----------------- ++
IPs.txt:
96.47.156.166:10200
96.47.88.7:14328
97.88.243.210:24598
98.201.217.101:23320
Error Here :
PROXY = P[0] # = 96.47.156.166:10200 #from the text file
IP,PORT = PROXY.split(":")
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "96.47.156.166", "10200")
i need it like this to work :
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "96.47.156.166", 10200) #withot ""
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
You need to convert PORT to an int:
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, IP, int(PORT))
Note that this will raise a ValueError if for some whatever reason PORT can't be converted, so you may want to catch it.
Depending on the structure of your file, it is most likely that PORT will include a '\n' in the end. You will need to get rid of it with strip before trying to convert it to an int.
try:
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, IP, int(PORT.strip()))
except ValueError:
print('Illegal port')

Check server status on Twisted

While I was writing simple message-based fileserver and client, I got the idea about checking fileserver status, but don't know how to realize this: just try to connect and disconnect from server (and how disconnect immediately, when server is not running, if using this way?) or maybe twisted/autobahn have some things, which help to get server status without creating "full connection"?
a) fileserver.py
import os
import sys
import json
from twisted.internet import reactor
from autobahn.twisted.websocket import WebSocketServerFactory, WebSocketServerProtocol, listenWS
CONFIG_TEMPLATE = ''
CONFIG_DATA = {}
class MessageBasedServerProtocol(WebSocketServerProtocol):
"""
Message-based WebSockets server
Template contains some parts as string:
[USER_ID:OPERATION_NAME:FILE_ID] - 15 symbols for USER_ID,
10 symbols for OPERATION_NAME,
25 symbols for FILE_ID
other - some data
"""
def __init__(self):
path = CONFIG_DATA['path']
base_dir = CONFIG_DATA['base_dir']
# prepare to working with files...
if os.path.exists(path) and os.path.isdir(path):
os.chdir(path)
if not os.path.exists(base_dir) or not os.path.isdir(base_dir):
os.mkdir(base_dir)
os.chdir(base_dir)
else:
os.makedir(path)
os.chdir(path)
os.mkdir(base_dir)
os.chdir(base_dir)
# init some things
self.fullpath = path + '/' + base_dir
def __checkUserCatalog(self, user_id):
# prepare to working with files...
os.chdir(self.fullpath)
if not os.path.exists(user_id) or not os.path.isdir(user_id):
os.mkdir(user_id)
os.chdir(user_id)
else:
os.chdir(self.fullpath + '/' + user_id)
def onOpen(self):
print "[USER] User with %s connected" % (self.transport.getPeer())
def connectionLost(self, reason):
print '[USER] Lost connection from %s' % (self.transport.getPeer())
def onMessage(self, payload, isBinary):
"""
Processing request from user and send response
"""
user_id, cmd, file_id = payload[:54].replace('[', '').replace(']','').split(':')
data = payload[54:]
operation = "UNK" # WRT - Write, REA -> Read, DEL -> Delete, UNK -> Unknown
status = "C" # C -> Complete, E -> Error in operation
commentary = 'Succesfull!'
# write file into user storage
if cmd == 'WRITE_FILE':
self.__checkUserCatalog(user_id)
operation = "WRT"
try:
f = open(file_id, "wb")
f.write(data)
except IOError, argument:
status = "E"
commentary = argument
except Exception, argument:
status = "E"
commentary = argument
raise Exception(argument)
finally:
f.close()
# read some file
elif cmd == 'READU_FILE':
self.__checkUserCatalog(user_id)
operation = "REA"
try:
f = open(file_id, "rb")
commentary = f.read()
except IOError, argument:
status = "E"
commentary = argument
except Exception, argument:
status = "E"
commentary = argument
raise Exception(argument)
finally:
f.close()
# delete file from storage (and in main server, in parallel delete from DB)
elif cmd == 'DELET_FILE':
self.__checkUserCatalog(user_id)
operation = "DEL"
try:
os.remove(file_id)
except IOError, argument:
status = "E"
commentary = argument
except Exception, argument:
status = "E"
commentary = argument
raise Exception(argument)
self.sendMessage('[%s][%s]%s' % (operation, status, commentary), isBinary=True)
if __name__ == '__main__':
if len(sys.argv) < 2:
print "using python fileserver_client.py [PATH_TO_config.json_FILE]"
else:
# read config file
CONFIG_TEMPLATE = sys.argv[1]
with open(CONFIG_TEMPLATE, "r") as f:
CONFIG_DATA = json.load(f)
# create server
factory = WebSocketServerFactory("ws://localhost:9000")
factory.protocol = MessageBasedServerProtocol
listenWS(factory)
reactor.run()
b) client.py
import json
import sys
import commands
from twisted.internet import reactor
from autobahn.twisted.websocket import WebSocketClientFactory, WebSocketClientProtocol, connectWS
CONFIG_TEMPLATE = ''
CONFIG_DATA = {}
class MessageBasedClientProtocol(WebSocketClientProtocol):
"""
Message-based WebSockets client
Template contains some parts as string:
[USER_ID:OPERATION_NAME:FILE_ID] - 15 symbols for USER_ID,
10 symbols for OPERATION_NAME,
25 symbols for FILE_ID
other - some data
"""
def onOpen(self):
user_id = CONFIG_DATA['user']
operation_name = CONFIG_DATA['cmd']
file_id = CONFIG_DATA['file_id']
src_file = CONFIG_DATA['src_file']
data = '[' + str(user_id) + ':' + str(operation_name) + ':' + str(file_id) + ']'
if operation_name == 'WRITE_FILE':
with open(src_file, "r") as f:
info = f.read()
data += str(info)
self.sendMessage(data, isBinary=True)
def onMessage(self, payload, isBinary):
cmd = payload[1:4]
result_cmd = payload[6]
if cmd in ('WRT', 'DEL'):
print payload
elif cmd == 'REA':
if result_cmd == 'C':
try:
data = payload[8:]
f = open(CONFIG_DATA['src_file'], "wb")
f.write(data)
except IOError, e:
print e
except Exception, e:
raise Exception(e)
finally:
print payload[:8] + "Successfully!"
f.close()
else:
print payload
reactor.stop()
if __name__ == '__main__':
if len(sys.argv) < 2:
print "using python fileserver_client.py [PATH_TO_config.json_FILE]"
else:
# read config file
CONFIG_TEMPLATE = sys.argv[1]
with open(CONFIG_TEMPLATE, "r") as f:
CONFIG_DATA = json.load(f)
# connection to server
factory = WebSocketClientFactory("ws://localhost:9000")
factory.protocol = MessageBasedClientProtocol
connectWS(factory)
reactor.run()
Find solution this issue: using callLater or deferLater for disconnect from server, if can't connect, but when all was 'OK', just take server status, which he says.
import sys
from twisted.internet.task import deferLater
from twisted.internet import reactor
from autobahn.twisted.websocket import WebSocketClientFactory, WebSocketClientProtocol, connectWS
CONFIG_IP = ''
CONFIG_PORT = 9000
def isOffline(status):
print status
class StatusCheckerProtocol(WebSocketClientProtocol):
def __init__(self):
self.operation_name = "STATUS_SRV"
self.user_id = 'u00000000000000'
self.file_id = "000000000000000000000.log"
def onOpen(self):
data = '[' + str(self.user_id) + ':' + str(self.operation_name) + ':' + str(self.file_id) + ']'
self.sendMessage(data, isBinary=True)
def onMessage(self, payload, isBinary):
cmd = payload[1:4]
result_cmd = payload[6]
data = payload[8:]
print data
reactor.stop()
if __name__ == '__main__':
if len(sys.argv) < 3:
print "using python statuschecker.py [IP] [PORT]"
else:
# read preferences
CONFIG_IP = sys.argv[1]
CONFIG_PORT = int(sys.argv[2])
server_addr = "ws://%s:%d" % (CONFIG_IP, CONFIG_PORT)
# connection to server
factory = WebSocketClientFactory(server_addr)
factory.protocol = StatusCheckerProtocol
connectWS(factory)
# create special Deffered, which disconnect us from some server, if can't connect within 3 seconds
d = deferLater(reactor, 3, isOffline, 'OFFLINE')
d.addCallback(lambda ignored: reactor.stop())
# run all system...
reactor.run()

Global variables and functions Python

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()
You didn't call proxycall() at all, so the variables were never set.
Call it first, then call web1():
proxycall()
web1()
Names don't just pop into existence just because you marked them as global in a function; Python names require assignment (binding) to materialize.
You need to call proxycall() before you can access ip globally:
proxycall()
web1()
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.
You need to call proxycall() to initialize ip
proxycall()
web1()
You need to initialize/define ip and port before using them. Call proxycall() and then 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()
ans:
192.168.0.1
8080

Categories

Resources