本文整理匯總了Python中webbrowser.open_new_tab方法的典型用法代碼示例。如果您正苦於以下問題:Python webbrowser.open_new_tab方法的具體用法?Python webbrowser.open_new_tab怎麽用?Python webbrowser.open_new_tab使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類webbrowser
的用法示例。
在下文中一共展示了webbrowser.open_new_tab方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: open_codespace
# 需要導入模塊: import webbrowser [as 別名]
# 或者: from webbrowser import open_new_tab [as 別名]
def open_codespace(cmd, client, plan_name, resource_group_name=None, codespace_id=None,
codespace_name=None, do_not_prompt=None):
token = client.write_environments_action(resource_group_name=resource_group_name, plan_name=plan_name)
if codespace_name:
codespace_id = _determine_codespace_id(
client, resource_group_name, plan_name, token, codespace_name, cli_ctx=cmd.cli_ctx)
codespace = cs_api.get_codespace(token.access_token, codespace_id, cli_ctx=cmd.cli_ctx)
if not do_not_prompt and codespace['state'] != 'Available':
msg = f"Current state of the codespace is '{codespace['state']}'." \
" Continuing will cause the environment to be resumed.\nDo you want to continue?"
user_confirmed = prompt_y_n(msg)
if not user_confirmed:
raise CLIError("Operation cancelled.")
domain = cs_config.get_service_domain(cmd.cli_ctx)
url = f"https://{domain}/environment/{codespace['id']}"
logger.warning("Opening: %s", url)
success = webbrowser.open_new_tab(url)
if not success:
raise CLIError("Unable to open browser")
示例2: open_in_browser
# 需要導入模塊: import webbrowser [as 別名]
# 或者: from webbrowser import open_new_tab [as 別名]
def open_in_browser(sf_basic_config, url, browser_name = '', browser_path = ''):
settings = sf_basic_config.get_setting()
if not browser_path or not os.path.exists(browser_path) or browser_name == "default":
webbrowser.open_new_tab(url)
elif browser_name == "chrome-private":
# os.system("\"%s\" --incognito %s" % (browser_path, url))
browser = webbrowser.get('"' + browser_path +'" --incognito %s')
browser.open(url)
else:
try:
# show_in_panel("33")
# browser_path = "\"C:\Program Files\Google\Chrome\Application\chrome.exe\" --incognito"
webbrowser.register('chromex', None, webbrowser.BackgroundBrowser(browser_path))
webbrowser.get('chromex').open_new_tab(url)
except Exception as e:
webbrowser.open_new_tab(url)
示例3: start
# 需要導入模塊: import webbrowser [as 別名]
# 或者: from webbrowser import open_new_tab [as 別名]
def start(self, block=False, open_browser=True, develop=False):
"""
Start the page services.
:param block: Should the method invocation block. (default: ``False``)
:param open_browser: Should a new tab be opened in a browser pointing to the started page. (default: ``True``)
:param develop: During development, changes to port for open browser to ``3000``.
(due to npm start, default ``False``)
"""
if self._started:
return
if self._offline:
self._element_updater.start()
return
self._message_handler.start()
self._server.start()
self._ws_server.start()
self._element_updater.start()
self._started = True
if open_browser:
port = 3000 if (develop or os.environ.get('AWE_DEVELOP')) else self._port
webbrowser.open_new_tab('http://localhost:{}'.format(port))
if block:
self.block()
示例4: on_menuitem_preview_browser_activate
# 需要導入模塊: import webbrowser [as 別名]
# 或者: from webbrowser import open_new_tab [as 別名]
def on_menuitem_preview_browser_activate(self, widget):
# Create a temporary HTML file
tf = tempfile.NamedTemporaryFile(delete = False)
self.temp_file_list.append(tf)
tf_name = tf.name
text = self.text_buffer.get_text(self.text_buffer.get_start_iter(), self.text_buffer.get_end_iter(), False)
dirname = os.path.dirname(self.name)
text = re.sub(r'(\!\[.*?\]\()([^/][^:]*?\))', lambda m, dirname=dirname: m.group(1) + os.path.join(dirname, m.group(2)), text)
try:
html_middle = markdown.markdown(text, self.default_extensions)
except:
try:
html_middle = markdown.markdown(text, extensions =self.safe_extensions)
except:
html_middle = markdown.markdown(text)
html = self.default_html_start + html_middle + self.default_html_end
tf.write(html.encode())
tf.flush()
# Load the temporary HTML file in the user's default browser
webbrowser.open_new_tab(tf_name)
示例5: opencov
# 需要導入模塊: import webbrowser [as 別名]
# 或者: from webbrowser import open_new_tab [as 別名]
def opencov(self, syncDir, job_type, job_id):
cov_web_indexhtml = syncDir + "/cov/web/index.html"
if not util.pprint_decorator_fargs(util.func_wrapper(os.path.exists, cov_web_indexhtml),
'Opening coverage html for {} job ID [{}]'.format(job_type, job_id),
indent=2, fail_msg=self.fail_msg):
return False
if self.test:
return True
webbrowser.open_new_tab(cov_web_indexhtml)
return True
# TODO: Add feature
# def opencov_abtests(self):
#
# control_sync = '{}/{}/afl-out'.format(self.job_token.rootdir, self.job_token.joba_id)
# exp_sync = '{}/{}/afl-out'.format(self.job_token.rootdir, self.job_token.jobb_id)
#
# if not self.opencov(control_sync, self.job_token.type, self.job_token.joba_id):
# return False
# if not self.opencov(exp_sync, self.job_token.type, self.job_token.jobb_id):
# return False
# return True
示例6: docs
# 需要導入模塊: import webbrowser [as 別名]
# 或者: from webbrowser import open_new_tab [as 別名]
def docs(ctx, output='html', rebuild=False, show=True, verbose=True):
"""Build the docs and show them in default web browser."""
sphinx_build = ctx.run(
'sphinx-build -b {output} {all} {verbose} docs docs/_build'.format(
output=output,
all='-a -E' if rebuild else '',
verbose='-v' if verbose else ''))
if not sphinx_build.ok:
fatal("Failed to build the docs", cause=sphinx_build)
if show:
path = os.path.join(DOCS_OUTPUT_DIR, 'index.html')
if sys.platform == 'darwin':
path = 'file://%s' % os.path.abspath(path)
webbrowser.open_new_tab(path)
# TODO: remove this when PyPI upload from Travis CI is verified to work
示例7: stackoverflow
# 需要導入模塊: import webbrowser [as 別名]
# 或者: from webbrowser import open_new_tab [as 別名]
def stackoverflow(error):
url = 'https://api.stackexchange.com/2.2/search/advanced?order=desc&migrated=False&sort=activity&body=%s&accepted=True&closed=False&site=stackoverflow&key=%s' % (error, key)
try:
response = requests.get(url, headers = headers)
if response.status_code == 200:
data = response.json()
result_dict = []
if len(data['items']) > 0:
webbrowser.open_new_tab(data['items'][0]['link'])
for i in range(1,min(6,len(data['items']))):
res_dict = {}
res_dict['title'] = data['items'][i]['title']
res_dict['link'] = data['items'][i]['link']
result_dict.append(res_dict)
print tabulate([[i['title'][:50],i['link']] for i in result_dict], headers = ['Title','Link'],tablefmt="simple_grid")
else:
print "Substantial answers not found"
else:
print "Api Issues"
except:
print "Network Issues"
示例8: _run_webserver
# 需要導入模塊: import webbrowser [as 別名]
# 或者: from webbrowser import open_new_tab [as 別名]
def _run_webserver(self):
"""
Starts the webserver on the given port.
"""
try:
os.chdir('./editor/dist')
self.httpd = TCPServer(('', self.port), QuietHTTPRequestHandler)
print("Editor started at port %d" % self.port)
url = 'http://localhost:%d/dettect-editor' % self.port
if not os.getenv('DeTTECT_DOCKER_CONTAINER'):
print("Opening webbrowser: " + url)
webbrowser.open_new_tab(url)
else:
print("You can open the Editor on: " + url)
self.httpd.serve_forever()
except Exception as e:
print("Could not start webserver: " + str(e))
示例9: click
# 需要導入模塊: import webbrowser [as 別名]
# 或者: from webbrowser import open_new_tab [as 別名]
def click(self, text: str):
values = [
ui.InputListItem(lambda: sublime.set_clipboard(text), "Copy"),
]
for match in url_matching_regex.findall(text):
values.insert(0, ui.InputListItem(lambda: webbrowser.open_new_tab(match[0]), "Open"))
if self.clicked_menu:
values[0].run()
self.clicked_menu.cancel()
return
values[0].text += "\t Click again to select"
self.clicked_menu = ui.InputList(values, text).run()
await self.clicked_menu
self.clicked_menu = None
示例10: on_settings
# 需要導入模塊: import webbrowser [as 別名]
# 或者: from webbrowser import open_new_tab [as 別名]
def on_settings(self) -> None:
import webbrowser
def about():
webbrowser.open_new_tab("https://github.com/daveleroy/sublime_debugger/blob/master/docs/setup.md")
def report_issue():
webbrowser.open_new_tab("https://github.com/daveleroy/sublime_debugger/issues")
values = Adapters.select_configuration(self).values
values.extend([
ui.InputListItem(lambda: ..., ""),
ui.InputListItem(report_issue, "Report Issue"),
ui.InputListItem(about, "About/Getting Started"),
])
ui.InputList(values).run()
示例11: invoke
# 需要導入模塊: import webbrowser [as 別名]
# 或者: from webbrowser import open_new_tab [as 別名]
def invoke(self, context, event):
import webbrowser
st = context.space_data
# get the selected text
text = self.get_selected_text(st.text)
# if no text is selected send the whole file
if text is None: text = st.text.as_string()
# send the text and receive the returned page
page = self.send_text(text)
if page is None:
return {'CANCELLED'}
# store the link in the clipboard
bpy.context.window_manager.clipboard = page
if context.scene.use_webbrowser:
try:
webbrowser.open_new_tab(page)
except:
self.report({'WARNING'}, "Error in opening the page %s." % (page))
return {'FINISHED'}
示例12: tool_help_button
# 需要導入模塊: import webbrowser [as 別名]
# 或者: from webbrowser import open_new_tab [as 別名]
def tool_help_button(self):
index = 0
found = False
#find toolbox corresponding to the current tool
for toolbox in self.lower_toolboxes:
for tool in self.sorted_tools[index]:
if tool == self.tool_name:
self.toolbox_name = toolbox
found = True
break
if found:
break
index = index + 1
#change LiDAR to Lidar
if index == 10:
self.toolbox_name = to_camelcase(self.toolbox_name)
#format subtoolboxes as for URLs
self.toolbox_name = self.camel_to_snake(self.toolbox_name).replace('/', '').replace(' ', '')
#open the user manual section for the current tool
webbrowser.open_new_tab("https://jblindsay.github.io/wbt_book/available_tools/" + self.toolbox_name + ".html#" + self.tool_name)
示例13: webeditor
# 需要導入模塊: import webbrowser [as 別名]
# 或者: from webbrowser import open_new_tab [as 別名]
def webeditor(obj, host="localhost", port=8000):
cleanup_tmp_folder()
url = "http://{host}:{port}/core/srv/tmp/webedit.html".format(
host=host,
port=port)
json_string = json.dumps(obj, sort_keys=True)
copy_html_template('webedit.html', json_string, "REPLACEJSON")
tab = webbrowser.open_new_tab(url)
# This runs forever and can only be shut down in the handler or by
# ctr+c
start_server(host=host, port=port, handler=WebEditHandler)
try:
obj = json.loads(
open_tmp_file('obj.json').readline(),
object_pairs_hook=OrderedDict)
except:
pass
cleanup_tmp_folder()
return obj
示例14: show
# 需要導入模塊: import webbrowser [as 別名]
# 或者: from webbrowser import open_new_tab [as 別名]
def show(self, fmt="html", header_block=None, footer_block=None):
"""
Show the block in a browser.
:param fmt: The format of the saved block. Supports the same output as `Block.save`
:return: Path to the block file.
"""
file_name = self._id[:user_config["id_precision"]] + "." + fmt
file_path = self.publish(os.path.expanduser(os.path.join(user_config["tmp_html_dir"], file_name)),
header_block=header_block, footer_block=footer_block)
try:
url_base = user_config["public_dir"]
except KeyError:
path = os.path.expanduser(file_path)
else:
path = urljoin(url_base, os.path.expanduser(user_config["tmp_html_dir"] + "/" + file_name))
webbrowser.open_new_tab(path)
return path
示例15: launch_external_viewer
# 需要導入模塊: import webbrowser [as 別名]
# 或者: from webbrowser import open_new_tab [as 別名]
def launch_external_viewer(fname):
"""
Open a file in an external viewer program.
Uses the ``xdg-open`` command on Linux, the ``open`` command on macOS, and
the default web browser on other systems.
Parameters
----------
fname : str
The file name of the file (preferably a full path).
"""
# Redirect stdout and stderr to devnull so that the terminal isn't filled
# with noise
run_args = dict(stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
# Open the file with the default viewer.
# Fall back to the browser if can't recognize the operating system.
if sys.platform.startswith("linux") and shutil.which("xdg-open"):
subprocess.run(["xdg-open", fname], check=False, **run_args)
elif sys.platform == "darwin": # Darwin is macOS
subprocess.run(["open", fname], check=False, **run_args)
else:
webbrowser.open_new_tab("file://{}".format(fname))