本文整理汇总了Python中urllib.request.pathname2url函数的典型用法代码示例。如果您正苦于以下问题:Python pathname2url函数的具体用法?Python pathname2url怎么用?Python pathname2url使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了pathname2url函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:leebivip,项目名称:sublimetext-markdown-preview,代码行数:53,代码来源:MarkdownPreview.py
示例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)
开发者ID:suraj813,项目名称:SOMClassifier,代码行数:53,代码来源:som_v4.py
示例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 )
开发者ID:AceOfDiamond,项目名称:gmate,代码行数:7,代码来源:__init__.py
示例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)))
开发者ID:edwardt,项目名称:algebraixlib,代码行数:7,代码来源:rdf.py
示例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")
开发者ID:arcanefoam,项目名称:ttc2016-live,代码行数:29,代码来源:test_presentation.py
示例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
开发者ID:Bob131,项目名称:obraz,代码行数:7,代码来源:obraz.py
示例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()
开发者ID:khughitt,项目名称:labnote,代码行数:27,代码来源:entry.py
示例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)
开发者ID:MSA-Argentina,项目名称:zaguan,代码行数:7,代码来源:run.py
示例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
开发者ID:sanfx,项目名称:linux-show-player,代码行数:7,代码来源:audio_utils.py
示例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."))
开发者ID:mchafu,项目名称:zget,代码行数:35,代码来源:put.py
示例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
开发者ID:curtwagner1984,项目名称:YAPO,代码行数:25,代码来源:ffmpeg_process.py
示例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
开发者ID:sunu,项目名称:localshare,代码行数:30,代码来源:localshare.py
示例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
开发者ID:sunu,项目名称:localshare,代码行数:26,代码来源:localshare.py
示例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
开发者ID:percy,项目名称:python-percy-client,代码行数:25,代码来源:resource_loader.py
示例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
开发者ID:philipzae,项目名称:litewelcome,代码行数:35,代码来源:lite-welcome.py
示例16: _create_layout
def _create_layout(self):
box = gui.widgetBox(self.controlArea,
orientation='horizontal')
self.varmodel = VariableListModel(parent=self)
self.attr_combo = gui.comboBox(box, self, 'selected_attr',
orientation=Qt.Horizontal,
label='Region attribute:',
callback=self.on_attr_change,
sendSelectedValue=True)
self.attr_combo.setModel(self.varmodel)
self.map_combo = gui.comboBox(box, self, 'selected_map',
orientation=Qt.Horizontal,
label='Map type:',
callback=self.on_map_change,
items=Map.all)
hexpand = QSizePolicy(QSizePolicy.Expanding,
QSizePolicy.Fixed)
self.attr_combo.setSizePolicy(hexpand)
self.map_combo.setSizePolicy(hexpand)
url = urljoin('file:',
pathname2url(os.path.join(
os.path.dirname(__file__),
'resources',
'owgeomap.html')))
self.webview = gui.WebviewWidget(self.controlArea, self, url=QUrl(url))
self.controlArea.layout().addWidget(self.webview)
QTimer.singleShot(
0, lambda: self.webview.evalJS('REGIONS = {};'.format({Map.WORLD: CC_WORLD,
Map.EUROPE: CC_EUROPE,
Map.USA: CC_USA})))
开发者ID:biolab,项目名称:orange3-text,代码行数:32,代码来源:owgeomap.py
示例17: path_to_url
def path_to_url(path):
"""Convert a system path to a URL."""
if os.path.sep == '/':
return path
return pathname2url(path)
开发者ID:Ohcanep,项目名称:mkdocs,代码行数:7,代码来源:__init__.py
示例18: make_repository
def make_repository(self, relpath, allow_revprop_changes=True):
"""Create a repository.
:return: Handle to the repository.
"""
abspath = os.path.join(self.test_dir, relpath)
repos.create(abspath)
if allow_revprop_changes:
if sys.platform == "win32":
revprop_hook = os.path.join(abspath, "hooks", "pre-revprop-change.bat")
f = open(revprop_hook, "w")
try:
f.write("exit 0\n")
finally:
f.close()
else:
revprop_hook = os.path.join(abspath, "hooks", "pre-revprop-change")
f = open(revprop_hook, "w")
try:
f.write("#!/bin/sh\n")
finally:
f.close()
os.chmod(revprop_hook, os.stat(revprop_hook).st_mode | 0o111)
if sys.platform == "win32":
return "file:%s" % pathname2url(abspath)
else:
return "file://%s" % abspath
开发者ID:vadmium,项目名称:subvertpy,代码行数:30,代码来源:__init__.py
示例19: _get_box_from_loc_name
def _get_box_from_loc_name(self, loc_name):
loc_name = pathname2url(loc_name)
api_url = 'https://maps.googleapis.com/maps/api/geocode/json?address={}'
api_url = api_url.format(loc_name)
req = urlopen(api_url)
body = ''.join(map(lambda x: x.decode('utf-8'), req.readlines()))
result = json.loads(body)['results'][0]
geo_box = result['geometry']['bounds']
box = [geo_box['southwest']['lng'],
geo_box['southwest']['lat'],
geo_box['northeast']['lng'],
geo_box['northeast']['lat']]
if self.expand:
mid = [(box[2] - box[0]) / 2 + box[0],
(box[3] - box[1]) / 2 + box[1]]
var_lng, var_lat = self._meter_to_geo(mid[0], mid[1], self.expand)
box[0] -= var_lng
box[1] -= var_lat
box[2] += var_lng
box[3] += var_lat
return box
开发者ID:TeraBytesMemory,项目名称:sprint,代码行数:26,代码来源:twitter.py
示例20: _get_uri
def _get_uri(self):
uri = self.filename
if not uri:
return
if uri.split(":")[0] not in ("http", "https", "file", "udp", "rtp", "rtsp"):
uri = "file:" + pathname2url(path.realpath(uri))
return uri
开发者ID:it-digin,项目名称:kivy,代码行数:7,代码来源:video_gstreamer.py
注:本文中的urllib.request.pathname2url函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论