def main(): AVAudioSession = cls('AVAudioSession') shared_session = msg(AVAudioSession, c_void_p, 'sharedInstance') category_set = msg(shared_session, c_bool, 'setCategory:error:', [c_void_p, c_void_p], nsstr('AVAudioSessionCategoryPlayAndRecord'), None) settings = msg(cls('NSMutableDictionary'), c_void_p, 'dictionary') kAudioFormatMPEG4AAC = 1633772320 msg(settings, None, 'setObject:forKey:', [c_void_p, c_void_p], ns_int(kAudioFormatMPEG4AAC), nsstr('AVFormatIDKey')) msg(settings, None, 'setObject:forKey:', [c_void_p, c_void_p], ns_float(44100.0), nsstr('AVSampleRateKey')) msg(settings, None, 'setObject:forKey:', [c_void_p, c_void_p], ns_int(2), nsstr('AVNumberOfChannelsKey')) output_path = os.path.abspath('Recording.m4a') out_url = nsurl_from_path(output_path) recorder = msg(cls('AVAudioRecorder'), c_void_p, 'alloc') recorder = msg(recorder, c_void_p, 'initWithURL:settings:error:', [c_void_p, c_void_p, c_void_p], out_url, settings, None) started_recording = msg(recorder, c_bool, 'record') if started_recording: print 'Recording started, press the "stop script" button to end recording...' try: while True: pass except KeyboardInterrupt: print 'Stopping...' msg(recorder, None, 'stop') msg(recorder, None, 'release') print 'Stopped recording.' import console console.quicklook(os.path.abspath('Recording.m4a'))
def main(): zip_dir=ZIP_DIR excludelist=EXCLUDES open_in_quicklook=False # set True to have Pythonista automatically open completed zip # (nice if you're always exporting zip immediately afterwards) excludelist.append(zip_dir) source_dir=os.path.join(os.path.expanduser("~"),"Documents") zip_dir_full=os.path.join(source_dir,zip_dir) fname=datetime.datetime.now().strftime("scripts-%Y%m%dT%H%M%S.zip") zip_file=os.path.join(zip_dir_full,fname) try: os.stat(zip_dir_full) except: os.mkdir(zip_dir_full) if not os.path.isdir(zip_dir_full): print "could not create zip dest dir {zdf}".format(zdf=zip_dir_full) sys.exit() make_zipfile(zip_file,source_dir,excludelist) print print "{fs} bytes written".format(fs=os.path.getsize(zip_file)) print "Done." if open_in_quicklook: console.quicklook(zip_file)
def main(): AVAudioSession = ObjCClass("AVAudioSession") NSURL = ObjCClass("NSURL") AVAudioRecorder = ObjCClass("AVAudioRecorder") shared_session = AVAudioSession.sharedInstance() category_set = shared_session.setCategory_error_(ns("AVAudioSessionCategoryPlayAndRecord"), None) settings = { ns("AVFormatIDKey"): ns(1633772320), ns("AVSampleRateKey"): ns(44100.00), ns("AVNumberOfChannelsKey"): ns(2), } output_path = os.path.abspath("Recording.m4a") out_url = NSURL.fileURLWithPath_(ns(output_path)) recorder = AVAudioRecorder.alloc().initWithURL_settings_error_(out_url, settings, None) started_recording = recorder.record() if started_recording: print('Recording started, press the "stop script" button to end recording...') try: while True: pass except KeyboardInterrupt: print("Stopping...") recorder.stop() recorder.release() print("Stopped recording.") import console console.quicklook(os.path.abspath("Recording.m4a"))
def tableview_did_select(self, tableview, section, row): u"""Called when the user selects a row. """ if not tableview.editing: fi = self.lists[section][row] if section == 0: console.show_activity() self.app.push_view(self.app.make_file_list(fi)) console.hide_activity() elif section == 1: group = fi.constants.group if fi.constants.ext in (u"htm", u"html"): webbrowser.open(u"file://" + fi.path) self.app.close() elif group in ("code", "code_tags", "text"): open_path(fi.path) self.app.close() elif group == "audio": spath = rel_to_app(fi.path.rsplit(u".", 1)[0]) sound.load_effect(spath) sound.play_effect(spath) elif group == "image": console.show_image(fi.path) else: self.app.close() time.sleep(ANIM_DELAY) console.quicklook(fi.path)
def PythonistaTest(): '''A test of the module for iOS devices running Pythonista''' import console import photos # Ask the user to either take a photo or choose an existing one capture = console.alert("Image2ASCII", button1="Take Photo", button2="Pick Photo") if capture == 1: im = photos.capture_image() elif capture == 2: im = photos.pick_image(original=False) photos.save_image(im) console.show_activity() out = image2ASCII(im, 200) outim = RenderASCII(out, bgcolor='#ededed') stitchImages(im, outim).show() console.hide_activity() outim.save('image.png') console.quicklook('image.png') mode = console.alert("Image2ASCII", "You can either:", "Share Text", "Share Image") if mode == 1: with open('output.txt', 'w') as f: f.write(out) console.open_in('output.txt') elif mode == 2: console.open_in('image.png') time.sleep(5) console.clear()
def quicklook(path): """ Show a preview of the file. :param path: path to file :type path: str """ console.quicklook(path)
def tableview_did_select(self, tableview, section, row): # Called when the user selects a row if not tableview.editing: fi = self.lists[section][row] if section == 0: console.show_activity() nav.push_view(make_file_list(fi)) console.hide_activity() elif section == 1: filetype = fi.fileinfo.filetype if fi.fileinfo.file_ext in ("htm", "html"): webbrowser.open("file://" + fi.path) nav.close() elif filetype in ("code", "code_tags", "text"): open_path(fi.path) nav.close() elif filetype == "audio": spath = rel_to_app(fi.path.rsplit(".", 1)[0]) sound.load_effect(spath) sound.play_effect(spath) elif filetype == "image": console.show_image(fi.path) else: console.quicklook(fi.path) nav.close()
def PythonistaTest(): '''A test of the module for iOS devices running Pythonista''' import console,photos,clipboard #Ask the user to either take a photo or choose an existing one capture = console.alert("Image2ASCII", button1="Take Photo", button2="Pick Photo") if capture == 1: im = photos.capture_image() elif capture == 2: im = photos.pick_image(original=False) photos.save_image(im) console.show_activity() out = image2ASCII(im, 200) outim = RenderASCII(out, bgcolor = '#ededed') stitchImages(im, outim).show() console.hide_activity() outim.save('image.jpg') console.quicklook('image.jpg') mode = console.alert("Image2ASCII", "You can either:","Share Text","Share Image") if mode == 1: file = open('output.txt', 'w') file.write(out) file.close() console.open_in('output.txt') elif mode == 2: console.open_in('image.jpg') time.sleep(5) console.clear()
def tableview_did_select(self, tableview, section, row): u"""Called when the user selects a row. """ if not tableview.editing: fi = self.lists[section][row] if section == 0: console.show_activity("Loading file list...") self.app.push_view(self.app.make_file_list(fi)) console.hide_activity() elif section == 1: group = fi.constants.group if fi.constants.ext in (u"htm", u"html"): webbrowser.open(u"file://" + fi.path) self.app.close() elif group in ("code", "code_tags", "text"): open_path(fi.path) self.app.close() elif group == "audio": spath = rel_to_app(fi.path.rsplit(u".", 1)[0]) sound.load_effect(spath) sound.play_effect(spath) elif group == "image": console.show_image(fi.path) else: self.app.close() time.sleep(ANIM_DELAY) console.quicklook(fi.path)
def tableview_did_select(self, tableview, section, row): # Called when the user selects a row if section == 0: if self.type == 0: # actions for folders if row == 0: # Go Here in Shellista nav.close() print("Launching Shellista...") try: from Shellista import Shell except ImportError as err: print("Failed to import Shellista: " + err.message) print("See note on Shellista integration at the top of filenav.py.") print("> logout") return shell = Shell() shell.prompt = '> ' shell.onecmd("cd " + self.path) print("> cd " + self.path) shell.cmdloop() elif self.type == 1: # actions for files if row == 0: # Quick Look nav.close() time.sleep(1) # ui thread will hang otherwise console.quicklook(self.path) elif row == 1: # Open in Editor open_path(self.path) nav.close() elif row == 2: # Copy & Open destdir = full_path(os.path.join(SCRIPT_ROOT, "temp")) if not os.path.exists(destdir): os.mkdir(destdir) destfile = full_path(os.path.join(destdir, os.path.basename(self.path).lstrip("."))) shutil.copy(self.path, destfile) editor.reload_files() open_path(destfile) nav.close() elif row == 3: # Copy & Open as Text destdir = full_path(os.path.join(SCRIPT_ROOT, "temp")) if not os.path.exists(destdir): os.mkdir(destdir) destfile = full_path(os.path.join(destdir, os.path.basename(self.path).lstrip(".") + ".txt")) shutil.copy(self.path, destfile) editor.reload_files() open_path(destfile) nav.close() elif row == 4: # Open In if console.open_in(self.path): nav.close() else: console.hud_alert("Failed to Open", "error")
def tableview_did_select(self, tableview, section, row): u"""Called when the user selects a row. """ key = self.lists[section][1][row][0] if key == "ios.quick_look": # Preview - Quick Look self.app.close() time.sleep(ANIM_DELAY) console.quicklook(self.fi.path) elif key == "editor.edit": # Open in Editor - editor open_path(self.fi.path) self.app.close() elif key == "editor.copy_edit": # Copy & Open - editor destdir = full_path( os.path.join(full_path(u"~"), u"Documents/temp")) if not os.path.exists(destdir): os.mkdir(destdir) destfile = full_path( os.path.join(destdir, self.fi.basename().lstrip(u"."))) shutil.copy(self.fi.path, destfile) editor.reload_files() open_path(destfile) self.app.close() elif key == "editor.copy_edit_txt": # Copy & Open as Text - editor destdir = full_path( os.path.join(full_path(u"~"), u"Documents/temp")) if not os.path.exists(destdir): os.mkdir(destdir) destfile = full_path( os.path.join(destdir, self.fi.basename().lstrip(u".") + u".txt")) shutil.copy(self.fi.path, destfile) editor.reload_files() open_path(destfile) self.app.close() elif key == "console.print_image": # Show in Console - console console.show_image(self.fi.path) elif key == "sound.play_sound": # Play Sound - sound spath = rel_to_app(self.fi.path.rsplit(u".", 1)[0]) sound.load_effect(spath) sound.play_effect(spath) elif key == "webbrowser.open": # Open Website - webbrowser webbrowser.open(u"file://" + self.fi.path) self.app.close() elif key == "ios.open_in": # Open In - External Apps if console.open_in(self.fi.path): self.app.close() else: console.hud_alert(u"Failed to Open", "error")
def main(): if not appex.is_running_extension(): print('This script is intended to be run from the sharing extension.') return url = appex.get_url() if not url: url = clipboard.get() console.hud_alert('url: ' + url) local_filename = download_file(url) console.hud_alert('copying to ' + local_filename) console.quicklook(local_filename)
def my_hook(d): if d['status'] == 'finished': console.hide_output() chosen = console.alert( 'Download Finished', "Video is already in Pythonista.\nWaht else do you want to do with it?", 'Quick Look', 'Open in', 'Save to Album') if chosen == 1: console.quicklook(d['filename']) elif chosen == 2: console.open_in(d['filename']) elif chosen == 3: save_video(d['filename'].encode('utf-8'))
def main(): if not appex.is_running_extension(): print('This script is intended to be run from the sharing extension.') return url = appex.get_url() if not url: print('No input URL found.') return #url = 'https://www.facebook.com/Spurs/?ref=ts&fref=ts' fname = DownloadFacebookVideo(url, 35) console.quicklook(fname) os.remove(fname)
def tableview_did_select(self, tableview, section, row): u"""Called when the user selects a row. """ key = self.lists[section][1][row][0] if key == "ios.quick_look": # Preview - Quick Look self.app.close() time.sleep(ANIM_DELAY) console.quicklook(self.fi.path) elif key == "editor.edit": # Open in Editor - editor open_path(self.fi.path) self.app.close() elif key == "editor.copy_edit": # Copy & Open - editor destdir = full_path(os.path.join(full_path(u"~"), u"Documents/temp")) if not os.path.exists(destdir): os.mkdir(destdir) destfile = full_path(os.path.join(destdir, self.fi.basename().lstrip(u"."))) shutil.copy(self.fi.path, destfile) editor.reload_files() open_path(destfile) self.app.close() elif key == "editor.copy_edit_txt": # Copy & Open as Text - editor destdir = full_path(os.path.join(full_path(u"~"), u"Documents/temp")) if not os.path.exists(destdir): os.mkdir(destdir) destfile = full_path(os.path.join(destdir, self.fi.basename().lstrip(u".") + u".txt")) shutil.copy(self.fi.path, destfile) editor.reload_files() open_path(destfile) self.app.close() elif key == "console.print_image": # Show in Console - console console.show_image(self.fi.path) elif key == "sound.play_sound": # Play Sound - sound spath = rel_to_app(self.fi.path.rsplit(u".", 1)[0]) sound.load_effect(spath) sound.play_effect(spath) elif key == "webbrowser.open": # Open Website - webbrowser webbrowser.open(u"file://" + self.fi.path) self.app.close() elif key == "ios.open_in": # Open In - External Apps if console.open_in(self.fi.path): self.app.close() else: console.hud_alert(u"Failed to Open", "error")
def main(): AVAudioSession = cls('AVAudioSession') shared_session = msg(AVAudioSession, c_void_p, 'sharedInstance') category_set = msg(shared_session, c_bool, 'setCategory:error:', [c_void_p, c_void_p], nsstr('AVAudioSessionCategoryPlayAndRecord'), None) settings = msg(cls('NSMutableDictionary'), c_void_p, 'dictionary') kAudioFormatMPEG4AAC = 1633772320 msg(settings, None, 'setObject:forKey:', [c_void_p, c_void_p], ns_int(kAudioFormatMPEG4AAC), nsstr('AVFormatIDKey')) msg(settings, None, 'setObject:forKey:', [c_void_p, c_void_p], ns_float(44100.0), nsstr('AVSampleRateKey')) msg(settings, None, 'setObject:forKey:', [c_void_p, c_void_p], ns_int(2), nsstr('AVNumberOfChannelsKey')) output_path = os.path.abspath('Recording.m4a') out_url = nsurl_from_path(output_path) recorder = msg(cls('AVAudioRecorder'), c_void_p, 'alloc') recorder = msg(recorder, c_void_p, 'initWithURL:settings:error:', [c_void_p, c_void_p, c_void_p], out_url, settings, None) started_recording = msg(recorder, c_bool, 'record') # https://forum.omz-software.com/topic/2178/save-audio-files-from-speech/10 if started_recording: import speech, sound speech.say('Whatever you want it to say') #time.sleep(however many seconds long is the recording) #im not sure if say() is asynchronous, if so, uncomment last line msg(recorder, None, 'stop') msg(recorder, None, 'release') #sound.play_effect(os.abspath('Recording.m4a')) #uncomment last line if you want it to play again #if started_recording: #print 'Recording started, press the "stop script" button to end recording...' #try: #while True: #pass #except KeyboardInterrupt: #print 'Stopping...' #msg(recorder, None, 'stop') #msg(recorder, None, 'release') #print 'Stopped recording.' import console console.quicklook(os.path.abspath('Recording.m4a'))
def displayImage(self): if len(self._instructionStack) == 1: data = self.imageData("PNG") suffix = ".png" else: data = self.imageData("GIF") suffix = ".gif" if data is None: return directory = tempfile.mkdtemp() fileName = "DrawBotista Preview" + suffix path = os.path.join(directory, fileName) f = open(path, "wb") f.write(data) f.close() console.quicklook(path) shutil.rmtree(directory)
def main(): if not appex.is_running_extension(): url = clipboard.get() console.hud_alert('from clipboard url: ' + url) else: url = appex.get_url() if not url: console.hud_alert('no url') url = clipboard.get() console.hud_alert('from clipboard url: ' + url) else: console.hud_alert('from appex url: ' + url) local_filename = download_binary_file(url) if local_filename: console.hud_alert('copying to ' + local_filename) if (local_filename.endswith('.mp4') or local_filename.endswith('.jpg') or local_filename.endswith('.jpeg') or local_filename.endswith('.png') or local_filename.endswith('.gif')): console.quicklook(local_filename)
def tableview_accessory_button_tapped(self, tableview, section, row): item = res_file[row] play_effect('ui:switch32') if index_data[item]['icon'] == 'iob:ios7_briefcase_32' and getsize( item) / 1000 / 1000 < 10: read_zip(item) elif not quicklook(item) and getsize(item) / 1000 / 1000 < 5: try: read_text(item) except: play_effect('digital:ZapThreeToneDown') hud_alert('不支持的文件类型', 'error', 1),
def quicklook(self): console.quicklook(self.filename)
else: src_path = './testpdf.pdf' src = PyPDF2.PdfFileReader(src_path) dst = PyPDF2.PdfFileWriter() for i in range(src.getNumPages()): p = src.getPage(i) with tempfile.NamedTemporaryFile(suffix='.pdf', delete=False) as f: tmp = PyPDF2.PdfFileWriter() tmp.addPage(p) tmp.write(f) f.close() console.quicklook(f.name) if console.alert( 'Keep?', 'Keep that page?', 'Yes', 'No', ) == 1: dst.addPage(p) with tempfile.NamedTemporaryFile(suffix='.pdf', delete=False) as f: dst.write(f) f.close() console.alert('Done', 'Show the results!', 'OK', hide_cancel_button=True) console.quicklook(f.name) os.remove(f.name)
data_dir = os.path.join(os.path.abspath('.'), 'Videos') if not os.path.isdir(data_dir): #print(data_dir) os.makedirs(data_dir) os.chdir(data_dir) #ßprint(os.path.abspath('.')) def DownloadFile(url, filename): res = requests.get(url) try: res.raise_for_status() except Exception as exc: print('There was a problem: %s' % (exc)) with open(filename, "wb") as code: code.write(res.content) # the URL below is copy from the console of the above script, I don't know why it quits without saving the file after download but it works in this script url = 'https://vsb01.520cc.cc/files/mp4/A/AIEdN.mp4?sk=tdVUWMc11zPLO17HpZ0rsg&se=1552373345' DownloadFile(url, 'temp.mp4') console.quicklook('temp.mp4') os.remove('temp.mp4')
def main(): images = [make_frame(float(i)/n_frames) for i in xrange(n_frames)] writeGif('animation.gif', images, duration/n_frames) console.quicklook('animation.gif')
def main(): images = [make_frame(float(i) / n_frames) for i in xrange(n_frames)] writeGif('animation.gif', images, duration / n_frames) console.quicklook('animation.gif')
def main():# -------------------- excludelist.append(zip_dir) source_dir=os.path.join(os.path.expanduser("~"),"Documents") zip_dir_full=os.path.join(source_dir,zip_dir) fname=datetime.datetime.now().strftime("scripts-%Y%m%dT%H%M%S.zip") zip_file=os.path.join(zip_dir_full,fname) try: os.stat(zip_dir_full) except: os.mkdir(zip_dir_full) if not os.path.isdir(zip_dir_full): print "could not create zip dest dir {zdf}".format(zdf=zip_dir_full) sys.exit() make_zipfile(zip_file,source_dir,excludelist) print print "{fs} bytes written".format(fs=os.path.getsize(zip_file)) print "Done." if open_in_quicklook: console.quicklook(zip_file) if open_in_other_app: console.open_in(zip_file) # -------------------- import os, sys, zipfile, datetime, console, time from dropbox import client, rest, session import webbrowser EXCLUDES=['local-packages', 'Backups', '.Trash'] # any folders you want to exclude from backup ZIP_DIR = 'Backups' # default folder where the finished .zip file will reside. # Folder will be created if doesn't exist and is automatically # excluded from the backup. def dropbox(APP_KEY, APP_SECRET, ACCESS_TYPE, upload_file): global client sess = session.DropboxSession(APP_KEY, APP_SECRET, ACCESS_TYPE) request_token = sess.obtain_request_token() url = sess.build_authorize_url(request_token) # Make the user sign in and authorize this token webbrowser.open(url, modal=False, stop_when_done=False) raw_input() # This will fail if the user didn't visit the above URL and hit 'Allow' access_token = sess.obtain_access_token(request_token) client = client.DropboxClient(sess) response = client.put_file(upload_file, upload_file) def main(): zip_dir=ZIP_DIR excludelist=EXCLUDES excludelist.append(zip_dir) source_dir=os.path.join(os.path.expanduser("~"),"Documents") zip_dir_full=os.path.join(source_dir,zip_dir) fname=datetime.datetime.now().strftime("Scripts Backup - %m%d%Y - %I:%M %p.zip") zip_file=os.path.join(zip_dir_full,fname) try: os.stat(zip_dir_full) except: os.mkdir(zip_dir_full) if not os.path.isdir(zip_dir_full): console.hud_alert("Could not create zip dest dir {zdf}".format(zdf=zip_dir_full), 'error', 1.5) sys.exit() make_zipfile(zip_file,source_dir,excludelist) bytes = "Backup Successfully Created - {fs} bytes written".format(fs=os.path.getsize(zip_file)) console.hud_alert(bytes, 'success', 1.5) dropbox('rso5vcsund16lw9','wqivu6pzm3ef93s', 'dropbox', zip_file) # http://stackoverflow.com/questions/1855095/how-to-create-a-zip-archive-of-a-directory def make_zipfile(output_filename, source_dir, excludelist): relroot = os.path.abspath(os.path.join(source_dir, os.pardir)) with zipfile.ZipFile(output_filename, "w", zipfile.ZIP_DEFLATED) as zip: for root, dirs, files in os.walk(source_dir,topdown=True): path_element=os.path.relpath(root,source_dir) # incredibly hacky and non-optimal way to implement an exclude list nextiter=False for path_ex in excludelist: if os.path.commonprefix([path_ex,path_element])==path_ex: nextiter=True break if nextiter==True: continue str = ("Adding {pe}").format(pe=path_element) console.show_activity(str) time.sleep(1) zip.write(root, os.path.relpath(root, relroot)) for file in files: filename = os.path.join(root, file) if os.path.isfile(filename): # regular files only arcname = os.path.join(os.path.relpath(root, relroot), file) zip.write(filename, arcname) console.hide_activity() if __name__ == "__main__": main()# --------------------
def start(): f = 'test.docx' outfile_path = os.path.abspath(f) console.quicklook(outfile_path) return 'Success!'
def quicklook(path): console.quicklook(path)
def main(args=None): ap = argparse.ArgumentParser() ap.add_argument('-c', '--current-file', action='store_true', help='Use file currently opened in editor as input') ap.add_argument('-e', '--edit-buffer', action='store_true', help='Use content of current editor buffer as input') ap.add_argument('infile', nargs='?', help='Input file name') args = ap.parse_args(args if args is not None else sys.argv[1:]) if args.edit_buffer or args.current_file: pdf_bn = make_pdf_filename(editor.get_path()) if args.current_file: with open(editor.get_path()) as f: md = f.read() elif args.edit_buffer: md = editor.get_text() elif args.infile: pfd_bn = make_pdf_filename(args.infile) with open(args.infile) as f: md = f.read() else: pdf_bn = 'markdown2pdf.pdf' try: choice = console.alert('Markdown to PDF', '', 'Show README', 'Convert Clipboard', 'Convert URL') except KeyboardInterrupt: return if choice == 1: md = __doc__ elif choice == 2: import clipboard md = clipboard.get() elif choice == 3: import re import clipboard try: cb = clipboard.get().strip() if not re.search('^(ht|f)tps?://', cb): cb = '' url = console.input_alert('Enter URL', 'Download Markdown from URL:', cb, 'Download') except KeyboardInterrupt: return else: import urllib2 import urlparse try: r = urllib2.urlopen(url) except urllib2.URLError as exc: print(exc) console.hud_alert("Download error (see console)", 'error') return else: md = r.read() url = urlparse.urlparse(r.geturl()) fn = make_pdf_filename(url.path) if fn: pdf_bn = fn if not md: return tempdir = tempfile.mkdtemp() pdf_path = join(tempdir, pdf_bn) console.show_activity() status = markdown2pdf(md, pdf_path) console.hide_activity() try: choice = console.alert('Select Ouput', '', 'Save to file...', 'Open in...', 'View') except KeyboardInterrupt: return if choice == 1: try: filename = console.input_alert( "Filename", "Enter PDF output filename\n(will overwrite existing files!):", pdf_bn, 'Save') os.rename(pdf_path, filename) except KeyboardInterrupt: return except (IOError, OSError) as exc: console.alert("Error", "Error writing PDF file:\n\n%s" % exc) return 1 elif choice == 2: console.open_in(pdf_path) elif choice == 3: console.quicklook(pdf_path) try: os.unlink(pdf_path) os.rmdir(tempdir) except: pass
def tableview_did_select(self, tableview, section, row): # Called when the user selects a row key = self.lists[section][1][row][0] if key == "shellista-cd": # Go Here - Shellista nav.close() print("Launching Shellista...") try: from Shellista import Shell except ImportError as err: print("Failed to import Shellista: " + err.message) print("See note on Shellista integration at the top of filenav.py.") print("> logout") return shell = Shell() shell.prompt = "> " shell.onecmd("cd " + self.fi.path) print("> cd " + self.fi.path) shell.cmdloop() elif key == "ios-qlook": # Preview - Quick Look nav.close() time.sleep(1) # ui thread will hang otherwise console.quicklook(self.fi.path) elif key == "pysta-edit": # Open in Editor - Pythonista open_path(self.fi.path) nav.close() elif key == "pysta-cpedit": # Copy & Open - Pythonista destdir = full_path(os.path.join(SCRIPT_ROOT, "temp")) if not os.path.exists(destdir): os.mkdir(destdir) destfile = full_path(os.path.join(destdir, self.fi.basename().lstrip("."))) shutil.copy(self.fi.path, destfile) editor.reload_files() open_path(destfile) nav.close() elif key == "pysta-cptxt": # Copy & Open as Text - Pythonista destdir = full_path(os.path.join(SCRIPT_ROOT, "temp")) if not os.path.exists(destdir): os.mkdir(destdir) destfile = full_path(os.path.join(destdir, self.fi.basename().lstrip(".") + ".txt")) shutil.copy(self.fi.path, destfile) editor.reload_files() open_path(destfile) nav.close() elif key == "console-printimg": # Show in Console - console console.show_image(self.fi.path) elif key == "sound-playsound": # Play Sound - sound spath = rel_to_app(self.fi.path.rsplit(".", 1)[0]) sound.load_effect(spath) sound.play_effect(spath) elif key == "webbrowser-open": # Open Website - webbrowser webbrowser.open("file://" + self.fi.path) nav.close() elif key == "ios-openin": # Open In - External Apps if console.open_in(self.fi.path): nav.close() else: console.hud_alert("Failed to Open", "error")
filename = 'result.pdf' while True: print 'Checking conversion status...' r = requests.get('http://webpagetopdf.com/status/%s/%s/%s' % (sid, cid, pid)) status_info = r.json() if 'file' in status_info: filename = status_info['file'] if verbose: print status_info if status_info['status'] == 'processing': time.sleep(1) elif status_info['status'] == 'success': break else: return None urllib.urlretrieve('http://webpagetopdf.com/download/%s/%s' % (sid, cid), filename) return filename if __name__ == '__main__': print 'Running demo...' page_url = 'http://pythonista-app.com' filename = convert_to_pdf(page_url) if filename: import console, os console.quicklook(os.path.abspath(filename)) else: print 'Conversion failed'
def photo_quicklook(self, sender): if self.values[self.photo_key] != '': console.quicklook(self.card_photo_path)
def main(args=None): ap = argparse.ArgumentParser() ap.add_argument('-c', '--current-file', action='store_true', help='Use file currently opened in editor as input') ap.add_argument('-e', '--edit-buffer', action='store_true', help='Use content of current editor buffer as input') ap.add_argument('infile', nargs='?', help='Input file name') args = ap.parse_args(args if args is not None else sys.argv[1:]) if args.edit_buffer or args.current_file: pdf_bn = make_pdf_filename(editor.get_path()) if args.current_file: with open(editor.get_path()) as f: md = f.read() elif args.edit_buffer: md = editor.get_text() elif args.infile: pfd_bn = make_pdf_filename(args.infile) with open(args.infile) as f: md = f.read() else: pdf_bn = 'markdown2pdf.pdf' try: choice = console.alert('Markdown to PDF', '', 'Show README', 'Convert Clipboard', 'Convert URL') except KeyboardInterrupt: return if choice == 1: md = __doc__ elif choice == 2: import clipboard md = clipboard.get() elif choice == 3: import re import clipboard try: cb = clipboard.get().strip() if not re.search('^(ht|f)tps?://', cb): cb = '' url = console.input_alert('Enter URL', 'Download Markdown from URL:', cb, 'Download') except KeyboardInterrupt: return else: import urllib2 import urlparse try: r = urllib2.urlopen(url) except urllib2.URLError as exc: print(exc) console.hud_alert("Download error (see console)", 'error') return else: md = r.read() url = urlparse.urlparse(r.geturl()) fn = make_pdf_filename(url.path) if fn: pdf_bn = fn if not md: return tempdir = tempfile.mkdtemp() pdf_path = join(tempdir, pdf_bn) console.show_activity() status = markdown2pdf(md, pdf_path) console.hide_activity() try: choice = console.alert('Select Ouput', '', 'Save to file...', 'Open in...', 'View') except KeyboardInterrupt: return if choice == 1: try: filename = console.input_alert("Filename", "Enter PDF output filename\n(will overwrite existing files!):", pdf_bn, 'Save') os.rename(pdf_path, filename) except KeyboardInterrupt: return except (IOError, OSError) as exc: console.alert("Error", "Error writing PDF file:\n\n%s" % exc) return 1 elif choice == 2: console.open_in(pdf_path) elif choice == 3: console.quicklook(pdf_path) try: os.unlink(pdf_path) os.rmdir(tempdir) except: pass
import console, requests url = 'http://bestanimations.com/Animals/Mammals/Horses/horse-walking-animated-gif1.gif' url = 'http://fc00.deviantart.net/fs71/f/2012/189/a/a/dressage_horse_animation_by_lauwiie1993-d56it04.gif' filename = url.split('/')[-1] with open(filename, 'wb') as out_file: out_file.write(requests.get(url).content) console.quicklook(filename)
import console import clipboard import os img = clipboard.get_image() if img: img.save('temp.jpg') console.quicklook('temp.jpg') os.remove('temp.jpg') else: print 'No image in clipboard.'
def tableview_did_select(self, tableview, section, row): # Called when the user selects a row key = self.lists[section][1][row][0] if key == "shellista-cd": # Go Here - Shellista nav.close() print("Launching Shellista...") try: from Shellista import Shell except ImportError as err: print("Failed to import Shellista: " + err.message) print("See note on Shellista integration at the top of filenav.py.") print("> logout") return shell = Shell() shell.prompt = '> ' shell.onecmd("cd " + self.fi.path) print("> cd " + self.fi.path) shell.cmdloop() elif key == "ios-qlook": # Preview - Quick Look nav.close() time.sleep(1) # ui thread will hang otherwise console.quicklook(self.fi.path) elif key == "pysta-edit": # Open in Editor - Pythonista open_path(self.fi.path) nav.close() elif key == "pysta-cpedit": # Copy & Open - Pythonista destdir = full_path(os.path.join(SCRIPT_ROOT, "temp")) if not os.path.exists(destdir): os.mkdir(destdir) destfile = full_path(os.path.join(destdir, self.fi.basename().lstrip("."))) shutil.copy(self.fi.path, destfile) editor.reload_files() open_path(destfile) nav.close() elif key == "pysta-cptxt": # Copy & Open as Text - Pythonista destdir = full_path(os.path.join(SCRIPT_ROOT, "temp")) if not os.path.exists(destdir): os.mkdir(destdir) destfile = full_path(os.path.join(destdir, self.fi.basename().lstrip(".") + ".txt")) shutil.copy(self.fi.path, destfile) editor.reload_files() open_path(destfile) nav.close() elif key == "console-printimg": # Show in Console - console console.show_image(self.fi.path) elif key == "sound-playsound": # Play Sound - sound spath = rel_to_app(self.fi.path.rsplit(".", 1)[0]) sound.load_effect(spath) sound.play_effect(spath) elif key == "webbrowser-open": # Open Website - webbrowser webbrowser.open("file://" + self.fi.path) nav.close() elif key == "ios-openin": # Open In - External Apps if console.open_in(self.fi.path): nav.close() else: console.hud_alert("Failed to Open", "error")
def table_remote_tapped(self, sender): self.check_enabled_btn() if not self.tv_remote.editing: rowtext = sender.items[sender.selected_row] filename_tapped = rowtext remote_dict = self.remote_dict[filename_tapped] full_path = remote_dict['full_path'] type = remote_dict['type'] if type == 'dir': try: self.sftp.listdir_attr(full_path) except IOError as e: console.hud_alert(str(e), 'error') logging.info('color:red {}'.format(e)) return self.remotePath = full_path self.refresh_remote_list() elif type == 'link': try: link_to = self.sftp.normalize(filename_tapped) except Exception as e: console.hud_alert('Invalid link?', 'error') logging.info('color:red {}'.format(e)) return info = self.sftp.stat(link_to) if str(info)[0] == 'd': self.remotePath = link_to self.refresh_remote_list() self.view['lb_remote'].text = self.remotePath elif str(info)[0] == '-': console.hud_alert('Target is file.Path is {}'.format(link_to)) self.remotePath = os.path.dirname(link_to) self.refresh_remote_list() self.view['lb_remote'].text = self.remotePath index = self.remote_list.index(os.path.basename(link_to)) self.tableview_did_select(self.tv_remote, 0, index) return elif type == 'file': result = console.alert("CleverSFTPClient","{}".format(filename_tapped),"Edit with Pythonista editor","Download and open", 'Execute') if result == 1: to_path = os.path.join(temp_path, 'CleverSFTPClient_'+filename_tapped) sftp_callback = self.progress(filename_tapped, filename_tapped, 'get') self.sftp.get(filename_tapped.strip(), to_path, sftp_callback) self.view.close() editor.open_file(to_path,True) console.hud_alert("When finish editing file, close current tab",'',5) wait_tab_closed(os.path.basename(to_path)) if console.alert("CleverSFTPClient","Save {}?".format(filename_tapped),'NOT Save', "Save", hide_cancel_button=True) == 2: self.view.present(hide_title_bar=True, orientations=['landscape']) sftp_callback = self.progress(filename_tapped, filename_tapped, 'put') self.progress_view.present('sheet') self.sftp.put(to_path, filename_tapped, sftp_callback) else: self.view.present(hide_title_bar=True, orientations=['landscape']) #self.progress_view.hidden = False elif result == 2: to_path = os.path.join(download_path, filename_tapped) self.progress_view.present('sheet') #self.progress_view.hidden = False sftp_callback = self.progress(filename_tapped, filename_tapped, 'get',open_path=to_path) try: self.sftp.get(filename_tapped, to_path, sftp_callback) except Exception as e: console.hud_alert(str(e)+' and retrying', 'error') logging.info('color:red {} and retrying.....'.format(e)) sftp_callback = self.progress(filename_tapped, filename_tapped, 'get',open_path=os.path.join(download_path, filename_tapped.strip())) self.sftp.get(filename_tapped.strip(), to_path, sftp_callback) #self.progress_view.close() console.quicklook(to_path) elif result == 3: cmd = console.input_alert('CleverSFTPClient','Run command','"{}"'.format(self.remote_dict[filename_tapped]['full_path']), 'Execute', hide_cancel_button=False) self.stash.csc_send('{}\n'.format(cmd)) self.stash.ui.present() self.stash.terminal.begin_editing()
#Ask the user to either take a photo or choose an existing one capture = console.alert("Image2ASCII", button1="Take Photo", button2="Pick Photo") if capture == 1: im = photos.capture_image() elif capture == 2: im = photos.pick_image(original=False) console.show_activity() out = image2ASCII(im, 200) outim = RenderASCII(out, bgcolor = '#ff0000') stitchImages(im, outim).show() console.hide_activity() outim.save('image.jpg') console.quicklook('image.jpg') mode = console.alert("Image2ASCII", "You can either:","Share Text","Share Image") if mode == 1: file = open('output.txt', 'w') file.write(out) file.close() console.open_in('output.txt') elif mode == 2: console.open_in('image.jpg') time.sleep(5) console.clear()
#coding: utf-8 import appex, console import os Files = appex.get_file_paths() print( Files ) print( os.path.basename( Files[ 0 ] ) ) mydir = os.path.realpath( Files[ 0 ] ).strip( os.path.basename( File[ 0 ] ) ) print mydir for fname in Files: with open( fname, 'r' ) as f: print( '\n' + fname ) print( 'First line reads: ' + f.readline().strip() ) print( 'Number of columns: ' + str( len( f.readline().strip().split( ',' ) ) ) ) console.quicklook( mydir )
def _quicklook(self): console.quicklook(self.filename)
def photo_quicklook(self, sender): if self.values[sender.name] == '': dialogs.hud_alert('There are no pictures associated') else: console.quicklook(self.values[sender.name])
url_list = generate_url_list(url, page_total) # 获取图像url pool = ThreadPool(4) down_url = pool.map(download_url, url_list) pool.close() pool.join() download_url_list = [] for i in down_url: for j in i: download_url_list.append(j) img_num = len(download_url_list) # 下载图像 console.clear() console.set_color(1,0,.8) console.set_font('Menlo',17) t1 = int(time.time()) pool2 = ThreadPool(6) pool2.map(download_img, download_url_list) pool2.close() pool2.join() t2 = int(time.time()) total_size = folder_size(folder_path) print('\n共计下载图片: '+str(len(download_url_list))+'张\n耗时: '+str(t2-t1)+'秒。\n文件夹大小:'+total_size+'\n文件默认保存在根目录:'+folder_name) file_list = [] for i in range(0, img_num): file_name = download_url_list[i].split('/')[-1] file_list.append(os.path.join(folder_path,file_name)) console.quicklook(file_list)