本文整理汇总了Python中urllib.request.pathname2url函数的典型用法代码示例。如果您正苦于以下问题:Python pathname2url函数的具体用法?Python pathname2url怎么用?Python pathname2url使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了pathname2url函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: repl_relative
def repl_relative(m, base_path, relative_path):
""" Replace path with relative path """
RE_WIN_DRIVE_PATH = re.compile(r"(^(?P<drive>[A-Za-z]{1}):(?:\\|/))")
link = m.group(0)
try:
scheme, netloc, path, params, query, fragment, is_url, is_absolute = parse_url(m.group('path')[1:-1])
if not is_url:
# Get the absolute path of the file or return
# if we can't resolve the path
path = url2pathname(path)
abs_path = None
if (not is_absolute):
# Convert current relative path to absolute
temp = os.path.normpath(os.path.join(base_path, path))
if os.path.exists(temp):
abs_path = temp.replace("\\", "/")
elif os.path.exists(path):
abs_path = path
if abs_path is not None:
convert = False
# Determine if we should convert the relative path
# (or see if we can realistically convert the path)
if (sublime.platform() == "windows"):
# Make sure basepath starts with same drive location as target
# If they don't match, we will stay with absolute path.
if (base_path.startswith('//') and base_path.startswith('//')):
convert = True
else:
base_drive = RE_WIN_DRIVE_PATH.match(base_path)
path_drive = RE_WIN_DRIVE_PATH.match(abs_path)
if (
(base_drive and path_drive) and
base_drive.group('drive').lower() == path_drive.group('drive').lower()
):
convert = True
else:
# OSX and Linux
convert = True
# Convert the path, url encode it, and format it as a link
if convert:
path = pathname2url(os.path.relpath(abs_path, relative_path).replace('\\', '/'))
else:
path = pathname2url(abs_path)
link = '%s"%s"' % (m.group('name'), urlunparse((scheme, netloc, path, params, query, fragment)))
except:
# Parsing crashed an burned; no need to continue.
pass
return link
示例2: search
def search(self,search_str,search_dir,depth=2):
# Depth -> number of top nodes to search. Default 2 (arbitrary) has been sufficient so far.
results = Counter() # {url:score}
dist_neu_searchq=Counter() # {nid:dist} Contains the similarity of each neuron to the aggregated search query
neuron_lookup = self._neu_index
neuron_labels = [[k for (k,n) in Counter(neuron.get_keylist()).most_common()[:10]] for neuron in self._neurons]
glomat = self._glomat # Global matrix. Contains similarity of each search term in the query to all neurons. Something like a cache.
conn = SQLCon()
searchvecs = [(x,list(conn.read(x))) for x in search_str.split() if not conn.read(x) is None] # Obtain (word,vec) of search terms
search_len = len(searchvecs)
for (w,v) in searchvecs: # For colour coding the map
try:
for nid in glomat[w]:
if glomat[w][nid] > dist_neu_searchq[nid]:
dist_neu_searchq[nid] += glomat[w][nid]/search_len
except KeyError:
glomat[w]={}
for nid,neuron in enumerate(self._neurons):
glomat[w][nid] = distance(neuron.get_weights(),v) # cosine similarity, hence 1 is best. 0 is bleh. -1 is opposite.
if glomat[w][nid] > dist_neu_searchq[nid]:
dist_neu_searchq[nid] += glomat[w][nid]/search_len
# Union of all doclists with minimum dist_from_neuron.
doclist = {}
for nid in dist_neu_searchq.most_common()[:depth]:
neuron = neuron_lookup[nid[0]]
doclist.update(neuron.get_top_docs(30))
files = (open(doc) for doc in doclist)
for json_file in files:
data = json.load(json_file)
centroids = data['centroids']
url = data['url']
json_file.close()
wc_sim = [distance(v,c) for c in centroids]
max_wc_sim = max(wc_sim)
results[url] += max_wc_sim/len(searchvecs)
results = OrderedDict(results.most_common(20))
htmlVars = {'query': search_str, 'results':results}
htmlCode = template.render(htmlVars)
result_path = os.path.join(search_dir,search_str+'.html')
map_path = os.path.join(search_dir,search_str+'_map.html')
with open(result_path,'w') as f:
f.write(htmlCode)
self.draw_SOM(search_str,dist_neu_searchq,neuron_labels,map_path)
result_path = "file://{}".format(pathname2url(result_path))
map_path = "file://{}".format(pathname2url(map_path))
webbrowser.open(result_path)
示例3: _open_file
def _open_file( self, filename ):
uri = self._rootdir + "/" + pathname2url(filename)
gio_file = Gio.file_new_for_uri(uri)
tab = self._window.get_tab_from_location(gio_file)
if tab == None:
tab = self._window.create_tab_from_location( gio_file, None, 0, 0, False, False )
self._window.set_active_tab( tab )
示例4: get_file_url
def get_file_url(path: str) -> str:
"""Return the file URL that corresponds to the file path ``path``.
If ``path`` is relative, it is converted into an absolute path before being converted into a
file URL.
"""
return _urlparse.urljoin('file:', _urlreq.pathname2url(_os.path.abspath(path)))
示例5: test_less_fields
def test_less_fields(self):
filename = os.path.join(os.path.dirname(__file__), 'resources/CSV_TEST_DATA_EMPTY_FIELDS.csv')
mediator = CsvMediator(first_row_is_headers=True, restval="Worcester")
uri = urljoin('file:', urllib.pathname2url(filename))
data = mediator.load(uri=uri, base_name="test", read_on_load=True)
self.assertEquals(len(data), 1) # Only one type of elements
row_class = list(data.keys())[0]
self.assertEquals(len(data[row_class]), 25) # Ten rows
row_element = data[row_class][0]
self.assertIsInstance(row_element, presentation.Row)
self.assertTrue(hasattr(row_element, "id"))
self.assertTrue(hasattr(row_element, "first_name"))
self.assertTrue(hasattr(row_element, "last_name"))
self.assertTrue(hasattr(row_element, "email"))
self.assertTrue(hasattr(row_element, "country"))
self.assertTrue(hasattr(row_element, "city"))
self.assertEqual(row_element.id, "1")
self.assertEqual(row_element.first_name, "Chris")
self.assertEqual(row_element.last_name, "Jordan")
self.assertEqual(row_element.email, "[email protected]")
self.assertEqual(row_element.country, "Indonesia")
self.assertEqual(row_element.city, "Worcester")
row_element = data[row_class][1]
self.assertEqual(row_element.id, "2")
self.assertEqual(row_element.first_name, "Edward")
self.assertEqual(row_element.last_name, "Williamson")
self.assertEqual(row_element.email, "[email protected]")
self.assertEqual(row_element.country, "Brazil")
self.assertEqual(row_element.city, "Vila Velha")
示例6: path2url
def path2url(path):
m = re.match(r'(.*)[/\\]index.html?$', path)
if m:
path = m.group(1) + os.path.sep
path = os.path.sep + path
url = pathname2url(path.encode(URL_ENCODING))
return url.decode('ASCII') if PY2 else url
示例7: __init__
def __init__(self, **kwargs):
"""Creates a lab notebook Entry object instance.
Parses the relevant file corresponding to the notebook entry and
attempts to determine an appropriate title to use for the entry, the
date the analysis was last modified, etc. and stores all of the
relevant information as a Entry instance.
Args:
filepath: Path to the file for which the lab notebook entry is
being created.
output_dir: The notebook HTML output directory. This will be
removed from the final path in order to generate a relative URL.
url_prefix: An optional URL prefix to be preprended to the entry.
"""
self.filepath = kwargs['filepath']
self.filename = os.path.basename(self.filepath)
self.dir_name = os.path.basename(os.path.dirname(self.filepath))
self.date = datetime.fromtimestamp(os.path.getmtime(self.filepath))
self.url = pathname2url(urljoin(kwargs['url_prefix'],
self.filepath.replace(kwargs['output_dir'] + "/", '')))
# set title
if 'title' in kwargs:
self.title = kwargs['title']
else:
self.title = self._get_entry_title()
示例8: load_window
def load_window():
controller = ColorsController()
cur_dir = os.path.dirname(os.path.abspath(__file__))
file_ = os.path.join(cur_dir, 'html/index.html')
uri = 'file://' + pathname2url(file_)
zaguan = Zaguan(uri, controller)
zaguan.run(debug=True)
示例9: gstDuration
def gstDuration(path):
try:
disc = GstPbutils.Discoverer()
discInfo = disc.discover_uri('file://' + url.pathname2url(path))
return int(discInfo.get_duration() / Gst.MSECOND)
except:
return -1
示例10: do_GET
def do_GET(self):
if self.path in map(
lambda x: urllib.pathname2url(os.path.join('/', x)),
self.server.allowed_basenames
):
utils.logger.info(_("Peer found. Uploading..."))
full_path = os.path.join(os.curdir, self.server.filename)
with open(full_path, 'rb') as fh:
maxsize = os.path.getsize(full_path)
self.send_response(200)
self.send_header('Content-type', 'application/octet-stream')
self.send_header(
'Content-disposition',
'inline; filename="%s"' % os.path.basename(
self.server.filename
)
)
self.send_header('Content-length', maxsize)
self.end_headers()
i = 0
while True:
data = fh.read(1024 * 8) # chunksize taken from urllib
if not data:
break
self.wfile.write(data)
if self.server.reporthook is not None:
self.server.reporthook(i, 1024 * 8, maxsize)
i += 1
self.server.downloaded = True
else:
self.send_response(404)
self.end_headers()
raise RuntimeError(_("Invalid request received. Aborting."))
示例11: ffmpeg_take_scene_screenshot_without_save
def ffmpeg_take_scene_screenshot_without_save(scene):
# When we get here we assume that the scene was alrady probed with ffprobe, therefore it has all the video metadata.
# {10 /x + y = 1} , {7200 / x + y = 300} where 10 and 7200 are the duration of the original video
# and 1 and 300 are the time in seconds where we should take the screen shot.
# EX if the video is 45 second long the screenshot will be taken on the 2nd second
# if the video duration is half an hour the screenshot will be taken at 74 seconds
# x=24.0468 y=0.584145
x = 24.0468
y = 0.584145
screenshot_time = seconds_to_string(int(scene.duration / x + y))
a = ffmpeg_take_screenshot(screenshot_time, scene.path_to_file)
if a['success']:
# print("Screenshot Taken")
dest_path = os.path.join(MEDIA_PATH, "scenes", str(scene.id), "thumb")
z = move_sample_movie_to_correct_dir(scene, True, "thumb.jpg", dest_path,
SCREENSHOT_OUTPUT_PATH, 'image')
time.sleep(1)
thumb_path = os.path.relpath(z, start='videos')
as_uri = urllib.pathname2url(thumb_path)
scene.thumbnail = as_uri
示例12: share
def share(filename, forever):
"""Share a file in the local network."""
ip = utils.get_ip()
# port = get_port()
# Bind to port 0. OS assigns a random open port.
server = httpserver.HTTPServer((ip, 0), utils.LocalFileHandler)
port = server.server_port
server.filename = filename
zc_info = zeroconf.ServiceInfo(
"_http._tcp.local.",
"%s._http._tcp.local." % filename,
utils.ip_to_bytes(ip), port, 0, 0,
{'filename': filename}
)
url = "http://" + ip + ":" + str(port) + "/" + urllib.pathname2url(filename)
zc_instance = zeroconf.Zeroconf()
try:
zc_instance.register_service(zc_info)
click.echo('Sharing %s at %s' % (filename, url))
if forever:
server.serve_forever(poll_interval=0.5)
else:
server.handle_request()
click.echo('File downloaded by peer. Exiting')
sys.exit(0)
except KeyboardInterrupt:
pass
示例13: map_files
def map_files():
"""List all available files."""
files = OrderedDict()
zc_instance = zeroconf.Zeroconf()
listener = utils.ServiceListener()
zeroconf.ServiceBrowser(zc_instance, "_http._tcp.local.", listener)
try:
# Give listener some time to discover available services.
time.sleep(0.5)
if not listener.services:
click.echo('No files available. Waiting ...')
while not listener.services:
time.sleep(0.5)
click.echo('Peer(s) found.')
for service in listener.services:
address = utils.bytes_to_ip(service.address)
port = service.port
filename = service.properties[b'filename'].decode('utf-8')
url = "http://" + address + ":" + str(port) + "/" + \
urllib.pathname2url(filename)
files[filename] = url
except KeyboardInterrupt:
sys.exit(0)
return files
示例14: build_resources
def build_resources(self):
resources = []
if not self.root_dir:
return resources
for root, dirs, files in os.walk(self.root_dir, followlinks=True):
for file_name in files:
path = os.path.join(root, file_name)
if os.path.getsize(path) > MAX_FILESIZE_BYTES:
continue
with open(path, 'rb') as f:
content = f.read()
path_for_url = pathname2url(path.replace(self.root_dir, '', 1))
if self.base_url[-1] == '/' and path_for_url[0] == '/':
path_for_url = path_for_url.replace('/', '' , 1)
resource_url = "{0}{1}".format(self.base_url, path_for_url)
resource = percy.Resource(
resource_url=resource_url,
sha=utils.sha256hash(content),
local_path=os.path.abspath(path),
)
resources.append(resource)
return resources
示例15: _build_app
def _build_app(self):
# build window
w = Gtk.Window()
w.set_position(Gtk.WindowPosition.CENTER)
w.set_wmclass('Welcome to Linux Lite', 'Welcome to Linux Lite')
w.set_title('Welcome to Linux Lite')
w.set_size_request(768, 496)
w.set_icon_from_file(os.path.join(self._data_path,
"icons/lite-welcome.png"))
# build webkit container
mv = LiteAppView()
# load our index file
file_out = os.path.abspath(os.path.join(self._data_path, 'frontend/index.html'))
uri = 'file://' + pathname2url(file_out)
mv.open(uri)
# build scrolled window widget and add our appview container
sw = Gtk.ScrolledWindow()
sw.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
sw.add(mv)
# build a an autoexpanding box and add our scrolled window
b = Gtk.VBox(homogeneous=False, spacing=0)
b.pack_start(sw, expand=True, fill=True, padding=0)
# add the box to the parent window and show
w.add(b)
w.connect('delete-event', self.close)
w.show_all()
self._window = w
self._appView = mv