def play_music(p, l):
""" Plays music """
respond("playing music", prepend_positive_response=True)
playlist = os.path.join(BASE_DIRECTORY, 'playlist.m3u')
extensions = [
".mp3",
".m4a",
".ogg",
".flac",
]
music_files = _get_all_files(preferences.get_music_dir(), extensions)
with open(playlist, 'w') as f:
for file in music_files:
f.write(file + "\n")
os.startfile(playlist)
python类startfile()的实例源码
def getQrcode(uuid):
print('Please scan the QR code.')
url = 'https://login.weixin.qq.com/qrcode/' + uuid
req = request.Request(url)
res = request.urlopen(req)
f = open(QRImagePath, 'wb')
f.write(res.read())
f.close()
time.sleep(1)
if sys.platform.find('darwin') >= 0:
subprocess.call(['open', QRImagePath])
elif sys.platform.find('linux') >= 0:
subprocess.call(['xdg-open', QRImagePath])
else:
os.startfile(QRImagePath)
def editFile(self, widgetList):
try:
filepath = widgetList.selectedItems()[0].text().split("|")[-1][1:]
if os.environ.get(MGEAR_SHIFTER_CUSTOMSTEP_KEY, ""):
editPath = os.path.join(
os.environ.get(
MGEAR_SHIFTER_CUSTOMSTEP_KEY, ""), filepath)
else:
editPath = filepath
if filepath:
if sys.platform.startswith('darwin'):
subprocess.call(('open', editPath))
elif os.name == 'nt':
os.startfile(editPath)
elif os.name == 'posix':
subprocess.call(('xdg-open', editPath))
else:
pm.displayWarning("Please select one item from the list")
except Exception:
pm.displayError("The step can't be find or does't exists")
def explore(path):
if path:
if os.path.exists(path):
path = os.path.dirname(path)
platform = os_qeury()
if platform == "darwin":
subprocess.Popen(['open',path])
return True
elif platform == "win32":
os.startfile(path)
return True
log.info("File dose not exist")
return False
log.info("No file name spacified")
return False
def run(filename):
if filename:
if os.path.exists(filename):
if sys.platform == "win32":
os.startfile(filename)
return True
else:
opener ="open" if sys.platform == "darwin" else "xdg-open"
subprocess.call([opener, filename])
return True
log.info("File dose not exist")
return False
log.info("No file name spacified")
return False
def getCaptcha(self):
captchaImgUrl = 'https://passport.lagou.com/vcode/create?from=register&refresh=%s' % time.time()
# ???????
f = open(CaptchaImagePath, 'wb')
f.write(self.session.get(captchaImgUrl, headers=HEADERS).content)
f.close()
# ???????
if sys.platform.find('darwin') >= 0:
subprocess.call(['open', CaptchaImagePath])
elif sys.platform.find('linux') >= 0:
subprocess.call(['xdg-open', CaptchaImagePath])
else:
os.startfile(CaptchaImagePath)
# ???????
captcha = input("???????(% s)????: " % CaptchaImagePath)
print('????????:% s' % captcha)
return captcha
def open_gui_editor(filename):
"""Opens default GUI text editor."""
if sys.platform == "win32":
os.startfile(filename)
elif sys.platform.startswith("darwin"):
try:
subprocess.call(["open", filename])
except FileNotFoundError:
print("Your default editor \"{}\" could not be opened.")
print("You can manually open \"{}\" if you want to edit it.".format(filename))
elif sys.platform.startswith("linux"):
try:
subprocess.call(["xdg-open", filename])
except FileNotFoundError:
print("Your default editor \"{}\" could not be opened.")
print("You can manually open \"{}\" if you want to edit it.".format(filename))
else:
print("Could not determine text editor.")
print("You can manually open \"{}\" if you want to edit it.".format(filename))
def _open_file_or_folder(self, path):
import os, subprocess
if not os.path.exists(path):
logger.warning("File/path does not exist: " + path)
msg = translate('statusbar', "File/path does not exist: ") + path
self.show_statusbar_warning_msg_slot(msg)
return
try:
QDesktopServices.openUrl(QUrl.fromLocalFile(path))
# if sys.platform.startswith('darwin'):
# subprocess.call(('open', path))
# elif os.name == 'nt':
# os.startfile(path)
# elif os.name == 'posix':
# subprocess.call(('xdg-open', path))
except:
self.show_statusbar_warning_msg_slot((translate('statusbar',"Cannot open file: %s")) % path)
def speak_from_os(self, speech_result_filename):
self.speak_result = self.get_abs_filename(speech_result_filename)
try:
self.speak_result = self.get_abs_filename(speech_result_filename)
# Check platform used
if platform.system() == "Linux":
os.system("xdg-open " + self.speak_result)
elif platform.system() == "Darwin":
os.system("afplay " + self.speak_result)
elif platform.system() == "Windows":
os.startfile(self.speak_result)
else:
os.system(self.speak_result)
except:
print("Default Audio Player for mp3 files is not set up, like vlc or something.")
try:
self.hibernate()
except:
print("Seems like eyed3 named package wasn't installed probably "
"Check back at the support tab in the main website. Or if you're "
"trying to close the application abruptly, keep pressing CTRL + C repeatedly.")
def do_print(self, evt):
# genero el renderizador con propiedades del PDF
t = Template(elements=[e.as_dict() for e in self.elements if not e.static])
t.add_page()
if not t['logo'] or not os.path.exists(t['logo']):
# put a default logo so it doesn't trow an exception
os.path.join(os.path.dirname(__file__), 'tutorial','logo.png')
t.set('logo', logo)
try:
t.render(self.filename +".pdf")
except:
if DEBUG and False:
import pdb;
pdb.pm()
else:
raise
if sys.platform=="linux2":
os.system("evince ""%s""" % self.filename +".pdf")
else:
os.startfile(self.filename +".pdf")
def _showQRCodeImg(self, str):
if self.commandLineQRCode:
qrCode = QRCode('https://login.weixin.qq.com/l/' + self.uuid)
self._showCommandLineQRCode(qrCode.text(1))
else:
url = 'https://login.weixin.qq.com/qrcode/' + self.uuid
params = {
't': 'webwx',
'_': int(time.time())
}
data = self._post(url, params, False)
if data == '':
return
QRCODE_PATH = self._saveFile('qrcode.jpg', data, '_showQRCodeImg')
if str == 'win':
os.startfile(QRCODE_PATH)
elif str == 'macos':
subprocess.call(["open", QRCODE_PATH])
else:
return
def genqrcode(self):
"""
@brief outprint the qrcode to stdout on macos/linux
or open image on windows
"""
if sys.platform.startswith('win'):
url = self.wx_conf['API_qrcode_img'] + self.uuid
params = {
't': 'webwx',
'_': int(time.time())
}
data = post(url, params, False)
if data == '':
return
qrcode_path = save_file('qrcode.jpg', data, './')
os.startfile(qrcode_path)
else:
str2qr_terminal(self.wx_conf['API_qrcode'] + self.uuid)
def OnHelp(self,e):
dlg = wx.MessageDialog(self, "Bonsu will attempt to open the"+os.linesep+"documentation with your default"+os.linesep+"browser. Continue?","Confirm Open", wx.OK|wx.CANCEL|wx.ICON_QUESTION)
result = dlg.ShowModal()
dlg.Destroy()
if result == wx.ID_OK:
path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'docs', 'bonsu.html')
if sys.platform.startswith('win'):
os.startfile(path)
elif sys.platform.startswith('darwin'):
from subprocess import Popen
Popen(['open', path])
else:
try:
from subprocess import Popen
Popen(['xdg-open', path])
except:
pass
def test_deprecated(self):
import nt
filename = os.fsencode(support.TESTFN)
with warnings.catch_warnings():
warnings.simplefilter("error", DeprecationWarning)
for func, *args in (
(nt._getfullpathname, filename),
(nt._isdir, filename),
(os.access, filename, os.R_OK),
(os.chdir, filename),
(os.chmod, filename, 0o777),
(os.getcwdb,),
(os.link, filename, filename),
(os.listdir, filename),
(os.lstat, filename),
(os.mkdir, filename),
(os.open, filename, os.O_RDONLY),
(os.rename, filename, filename),
(os.rmdir, filename),
(os.startfile, filename),
(os.stat, filename),
(os.unlink, filename),
(os.utime, filename),
):
self.assertRaises(DeprecationWarning, func, *args)
def create_py_file(file1,file2):
with open(file1.name, 'rb') as file_n1:
with open(file2.name, 'rb') as file_n2:
if not os.path.exists('/root/pyJoiner_output'):
os.mkdir('/root/pyJoiner_output')
with open('/root/pyJoiner_output/py_file.pyw', 'w') as py_file:
py_file.write('''import os
def join(file,file_name, file_extension):
if not os.path.exists(os.environ["TEMP"]+os.sep+file_name+file_extension):
with open(os.environ["TEMP"]+os.sep+file_name+file_extension,"wb") as output_file:
output_file.write(file)
os.startfile(os.environ["TEMP"]+os.sep+file_name+file_extension)
file1 = %s
file2 = %s
join(file1, "output_file1", "%s")
join(file2, "output_file2", "%s") ''' %( str(file_n1.read()), str(file_n2.read()), file1.extension, file2.extension))
def open_stream_in_browser(self, event):
stream_url = urlparse(self.stream.url)
netloc = stream_url.netloc
path = stream_url.path
if "twitch" in netloc:
path = stream_url.path + "/chat"
if "youtube" in netloc:
path = path.replace("watch", "live_chat")
correct_url = (stream_url.scheme, netloc, path, stream_url.params, stream_url.query, stream_url.fragment)
url = urlunparse(correct_url)
os = platform.system()
if os == OS.WINDOWS:
os2.startfile(url)
else:
webbrowser.open(url)
def _create_image_from_map(map_file, out_img, format):
out_img += ".%s" % format
#print out_img
params = ["shp2img", "-m", map_file, "-i", format, "-o", out_img]
os.environ['PATH'] = DLL_LOCATION + ';' + os.environ['PATH']
p = Popen(params, stdout=PIPE, bufsize=1)
with p.stdout:
for line in iter(p.stdout.readline, b''):
print(line)
p.wait() # wait for the subprocess to exit
#os.startfile(out_img)
return out_img
def create_image_from_map(map_file, dll_location):
of = tempfile.NamedTemporaryFile(delete=False, suffix=".png", prefix="tmp_")
of.close()
logging.debug("Creating file %s", of.name)
# [SHP2IMG] -m [MAPFILE] -i png -o [RESULT]
params = ["shp2img","-m", map_file,"-i","png","-o", of.name]
os.environ['PATH'] = dll_location + ';' + os.environ['PATH']
os.environ['PROJ_LIB'] = os.path.join(dll_location, "proj\SHARE")
logging.debug(" ".join(params))
p = Popen(params, stdout=PIPE, bufsize=1)
with p.stdout:
print(map_file)
for line in iter(p.stdout.readline, b''):
print(line)
p.wait() # wait for the subprocess to exit
os.startfile(of.name)
def _view_file(path):
'''
Open a file using the default application.
:param path: Path to be opened.
:type path: str
'''
try:
if sys.platform.startswith('darwin'):
r = subprocess.call(('open', path))
if r: raise RuntimeError('Subprocess failed to open')
elif os.name == 'nt':
os.startfile(path)
elif os.name == 'posix':
r = subprocess.call(('xdg-open', path))
if r: raise RuntimeError('Subprocess failed to open')
except:
# If all fails, try to use webbrowser
import webbrowser
webbrowser.open(path)
#=============================================================================
# METADATA
#=============================================================================
def _send(self, **kwargs):
recipient = kwargs.get('recipient')
subject = kwargs.get('subject')
text = kwargs.get('text')
uri = "mailto:"
if recipient:
uri += str(recipient)
if subject:
uri += "?" if not "?" in uri else "&"
uri += "subject="
uri += quote(str(subject))
if text:
uri += "?" if not "?" in uri else "&"
uri += "body="
uri += quote(str(text))
try:
os.startfile(uri)
except WindowsError:
print("Warning: unable to find a program able to send emails.")
def test_deprecated(self):
import nt
filename = os.fsencode(support.TESTFN)
with warnings.catch_warnings():
warnings.simplefilter("error", DeprecationWarning)
for func, *args in (
(nt._getfullpathname, filename),
(nt._isdir, filename),
(os.access, filename, os.R_OK),
(os.chdir, filename),
(os.chmod, filename, 0o777),
(os.getcwdb,),
(os.link, filename, filename),
(os.listdir, filename),
(os.lstat, filename),
(os.mkdir, filename),
(os.open, filename, os.O_RDONLY),
(os.rename, filename, filename),
(os.rmdir, filename),
(os.startfile, filename),
(os.stat, filename),
(os.unlink, filename),
(os.utime, filename),
):
self.assertRaises(DeprecationWarning, func, *args)
def btn_solve_on_click(self):
if self.grp is None or self.img is None:
tkMessageBox.showerror("Error", "Please load a maze first!")
return
self.perform_process(lambda: self.traverse_graph(), "Traversing graph...")
self.perform_process(lambda: self.write_to_file(), "Writing to file...")
tkMessageBox.showinfo("Info",
"Solved the maze in " + str(self.steps) + " steps!\n" +
"Path length:\t\t%d\n" % self.graph_traverser.path_length +
"Graph loading time:\t\t%.5lfs\n" % self.exec_time +
"Graph traverse time:\t\t%.5lfs\n" % (self.traverse_time_end - self.traverse_time_start) +
"File writing time:\t\t%.5lfs\n" % (self.imgwrite_time_end - self.imgwrite_time_start) +
"Total execution time:\t\t%.5lfs" % (self.exec_time + (self.imgwrite_time_end - self.traverse_time_start))
)
if self.show_solution.get() == True:
# Showing solution in new window
if sys.platform.startswith('linux'):
subprocess.call(["xdg-open", self.output_path])
else:
os.startfile(self.output_path)
def open_file_in_os(filename):
if sys.platform.startswith('darwin'):
subprocess.call(['open', filename])
elif os.name == 'nt':
os.startfile(filename)
elif os.name == 'posix':
subprocess.call(['xdg-open', filename])
##
# @brief
#
# @param chemin
# @param prof
# @param out
#
# @return
def execute(self, context):
import os
folder_path = bpy.path.abspath("//img")
for file in os.listdir(folder_path):
if file.lower().endswith(('.psd', '.kra')):
import sys
import subprocess
file_path = folder_path + "/" + file
if sys.platform.startswith('darwin'):
subprocess.call(('open', file_path))
elif os.name == 'nt':
os.startfile(file_path)
elif os.name == 'posix':
subprocess.call(('xdg-open', file_path))
return {'FINISHED'}
def launch(path):
if hasattr(os, 'startfile'):
os.startfile(path)
elif sys.platform == 'linux':
subprocess.call(['xdg-open', path])
elif sys.platform == 'darwin':
subprocess.call(['open', path])
def open(self, url, new=0, autoraise=True):
try:
os.startfile(url)
except WindowsError:
# [Error 22] No application is associated with the specified
# file for this operation: '<URL>'
return False
else:
return True
def configure_menu(self):
"Configure the (context) Menu widget."
# Shortcut for narrowing the search.
self.__menu.add_command(label='Search Directory',
command=self.search_dir)
self.__menu.add_separator()
# Operations committed on directory.
self.__menu.add_command(label='Remove Directory', command=self.rm_dir)
self.__menu.add_command(label='Remove Files', command=self.rm_files)
self.__menu.add_separator()
# Operations that recurse on sub-directories.
self.__menu.add_command(label='Remove Sub-directories',
command=self.rm_subdirs)
self.__menu.add_command(label='Remove Sub-files',
command=self.rm_subfiles)
self.__menu.add_separator()
# Operations that remove empty directories and files.
self.__menu.add_command(label='Remove Empty Directories',
command=self.rm_empty_dirs)
self.__menu.add_command(label='Remove Empty Files',
command=self.rm_empty_files)
# Only add "Open Directory" command on Windows.
if hasattr(os, 'startfile'):
self.__menu.add_separator()
self.__menu.add_command(label='Open Directory',
command=self.open_dir)
########################################################################
# This property is used to control access to operations.
def open_dir(self):
"Open up the current directory (only available on Windows)."
os.startfile(TreeviewNode.current(self.__tree).path)
########################################################################
# Execute actions requested by context menu.
def create_path(self, path, name):
# If the user is running Windows ...
if hasattr(os, 'startfile'):
# Create a new tag for the path.
self.__path_id += 1
tag = 'path' + str(self.__path_id)
# Add the text and create an opening command.
self.__text.insert(tkinter.END, name, ('dynamic_link', tag))
self.__text.tag_bind(tag, '<1>', lambda event: os.startfile(path))
else:
# Insert a link that does not do anything.
self.__text.insert(tkinter.END, name, 'static_link')
def open_file_associated(filepath):
if filepath:
if env_mode.get_platform() == 'Linux':
subprocess.call(('xdg-open', filepath))
else:
os.startfile(filepath)