def episode_gp(): pya.hotkey('alt', 'a') pya.typewrite(['tab'] * 4, interval=0.1) gp = pyperclip.copy('empty') pya.hotkey('ctrl', 'c') gp = pyperclip.paste() return gp
def run(self): recent_value = "" while not self._stopping: if pyperclip.paste() != recent_value: recent_value = pyperclip.paste() process(recent_value) time.sleep(self._pause)
def main(): try: druglist = set(load_jt('druglist.json')) except: druglist = set() query_list = generate_querylist() Delay(1) drugname = '' for query in query_list: for i in range(1,51): print 'Now crawling %s - %s' % (query, i) Delay(0.5) enter_query(query, t = 0.1) Delay(4) Down(i, dl=0.1) Enter(dl=0.5) Ctrl_a(dl=0.5) Ctrl_c(dl=0.5) try: if pyperclip.paste() == drugname: # 如过跟上一次重复,就跳过 break else: drugname = pyperclip.paste() druglist.add(drugname) dump_jt(list(druglist), 'druglist.json', replace = True) except: pass
def run(self): clipboard = pyperclip.paste() settings = QtCore.QSettings('glimmer', 'glimmer') print 'Monitoring clipboard.' while True: if (pyperclip.paste() != clipboard and pyperclip.paste() is not None): clipboard = pyperclip.paste() pyperclip.copy("") time.sleep(0.35) if clipboard == pyperclip.paste(): print 'Double copy detected, trying to make a POST now.' try: post(clipboard, settings.value('apiKey')) except ConnectionError: print 'Hmm, can\'t connect to the server bud.' except: print "Something went wrong, couldn't POST that." else: print 'Looks like you didn\'t copy twice bud.' pyperclip.copy(clipboard) else: pass time.sleep(0.1)
def mode_clipboard_watch(options): """Clipboard Watch Mode: watches for a new string on the clipboard, and tries to fetch that URL""" articles = set() failures = set() print('Hello, this is news-scraper. Copy a URL to start!') print('To quit, press CTRL+C in this window.\n') url = pyperclip.paste() while True: try: tmp_value = pyperclip.paste() if tmp_value != url: url = tmp_value print('Fetching article...') if options.debug: print("Value changed: %s" % str(url)[:100]) article = _get_article(url=url, bodyLines=options.bodyLines, debug=options.debug) if (article): articles.add(article) else: failures.add(url) time.sleep(0.2) except KeyboardInterrupt: break _output(articles, options.outputFile, failures, options.failureFile)
def address_scrape(): dob = pyperclip.copy('na') pya.moveTo(600, 175, duration=0.1) pya.click(button='right') pya.moveRel(55, 65) pya.click() dob = pyperclip.paste() street = pyperclip.copy('na') pya.moveTo(500, 240, duration=0.1) pya.click(button='right') pya.moveRel(55, 65) pya.click() street = pyperclip.paste() suburb = pyperclip.copy('na') pya.moveTo(330, 285, duration=0.1) pya.click(button='right') pya.moveRel(55, 65) pya.click() suburb = pyperclip.paste() postcode = pyperclip.copy('na') pya.moveTo(474, 285, duration=0.1) pya.dragTo(450, 285, duration=0.1) pya.moveTo(474, 285, duration=0.1) pya.click(button='right') pya.moveRel(55, 65) pya.click() postcode = pyperclip.paste() address = street + ' ' + suburb + ' ' + postcode return (address, dob)
def episode_get_mcn_and_ref(): # get mcn mcn = pyperclip.copy('na') pya.moveTo(424, 474, duration=0.1) pya.dragTo(346, 474, duration=0.1) pya.hotkey('ctrl', 'c') mcn = pyperclip.paste() pya.moveTo(424, 474, duration=0.1) pya.click(button='right') pya.moveTo(481, 268, duration=0.1) pya.click() mcn = pyperclip.paste() mcn = mcn.replace(' ', '') # get ref ref = pyperclip.copy('na') pya.moveTo(500, 475, duration=0.1) pya.dragRel(-8, 0, duration=0.1) pya.hotkey('ctrl', 'c') ref = pyperclip.paste() pya.moveRel(8, 0, duration=0.1) pya.click(button='right') pya.moveTo(577, 274, duration=0.1) pya.click() ref = pyperclip.paste() return mcn, ref
def test_fsl(original, flipped): """Test flipping all slashes/backslashes.""" assert slbsl.fsl(original) == flipped assert pyperclip.paste() == flipped assert slbsl.fsl(flipped) == original assert pyperclip.paste() == original
def main(): while True: if mailto.canaccept(pyperclip.paste()): a = pyperclip.paste() pyperclip.copy(mailto.fix(pyperclip.paste())) print 'Fixed ' + a + ' into ' + pyperclip.paste() time.sleep(1)
def on_release(key): global edicao global link_e global res global semi_res try: key = key.char except: pass if key == u'q': if semi_res is not None: res.append(copy.copy(semi_res)) semi_res = { u'edicao': edicao, u'titulo': pyperclip.paste(), u'link': link_e} if key == u'w': semi_res['subtitulo'] = pyperclip.paste() if key == u'e': semi_res['tags'] = pyperclip.paste() if key == keyboard.Key.esc: # Stop listener return False
def run(self): while not self._stopping: # print 'Producer' if self._current_value != pyperclip.paste(): self._current_value = pyperclip.paste() self._queue.put(pyperclip.paste()) print ' [q] ' + pyperclip.paste() time.sleep(self._pause)
def run(self): recent_value = "" while not self._stopping: if pyperclip.paste() != recent_value: recent_value = pyperclip.paste() print "print from watcher.run() "+recent_value if __parser__.url(pyperclip.paste()) is True: __modules__['print_url'].run(pyperclip.paste()) time.sleep(self._pause)
def job(file,mode): if mode == 1: url = upload_with_full_Path(file) if mode == 2: url = upload_with_full_Path_cmd(file) pyperclip.copy(url) pyperclip.paste() print url with open('Markdown-格式外链.txt', 'a') as f: f.write(url+'\n')
def __init__(self): QtGui.QDialog.__init__(self) self.setupUi(self) self.aria = Aria2Manager() self.edtDir.setText(HOME_DIR + '/Downloads') # Monitor clipboard for URLs if len(clip.paste()) > 4: if clip.paste()[:4] == 'http' or clip.paste()[:3] == 'ftp': self.edtUrl.setText(clip.paste())
def test_wtf(path): # smoke test for now with swallow_outputs() as cmo: wtf(dataset=path) assert_not_in('## dataset', cmo.out) assert_in('## configuration', cmo.out) # Those sections get sensored out by default now assert_not_in('user.name: ', cmo.out) with chpwd(path): with swallow_outputs() as cmo: wtf() assert_not_in('## dataset', cmo.out) assert_in('## configuration', cmo.out) # now with a dataset ds = create(path) with swallow_outputs() as cmo: wtf(dataset=ds.path) assert_in('## configuration', cmo.out) assert_in('## dataset', cmo.out) assert_in('path: {}'.format(ds.path), cmo.out) # and if we run with all sensitive for sensitive in ('some', True): with swallow_outputs() as cmo: wtf(dataset=ds.path, sensitive=sensitive) # we fake those for tests anyways, but we do show cfg in this mode # and explicitly not showing them assert_in('user.name: %s' % _HIDDEN, cmo.out) with swallow_outputs() as cmo: wtf(dataset=ds.path, sensitive='all') assert_not_in(_HIDDEN, cmo.out) # all is shown assert_in('user.name: ', cmo.out) skip_if_no_module('pyperclip') # verify that it works correctly in the env/platform import pyperclip with swallow_outputs() as cmo: try: pyperclip.copy("xxx") pyperclip_works = pyperclip.paste().strip() == "xxx" wtf(dataset=ds.path, clipboard=True) except (AttributeError, pyperclip.PyperclipException) as exc: # AttributeError could come from pyperclip if no DISPLAY raise SkipTest(exc_str(exc)) assert_in("WTF information of length", cmo.out) assert_not_in('user.name', cmo.out) if not pyperclip_works: # Some times does not throw but just fails to work raise SkipTest( "Pyperclip seems to be not functioning here correctly") assert_not_in('user.name', pyperclip.paste()) assert_in(_HIDDEN, pyperclip.paste()) # by default no sensitive info assert_in("cmd:annex:", pyperclip.paste()) # but the content is there
def job(file, mode): if mode == 1: url = upload_with_full_Path(file) if mode == 2: url = upload_with_full_Path_cmd(file) pyperclip.copy(url) pyperclip.paste() print url with open('MARKDOWN_FORMAT_URLS.txt', 'a') as f: image = '![' + url + ']' + '(' + url + ')' + '\n' f.write(image + '\n')
def main(): text = db.get_lastest_paste() while True: if text == pyperclip.paste(): sleep(1) continue text = pyperclip.paste() print("Detected new text", text) db.save_new_paste(text) sleep(0.5)
def console(): ''' cli hook return -- integer -- the exit code ''' default_f = os.path.join(os.getcwd(), datetime.datetime.now().strftime("%Y-%m-%d-%H:%M.txt")) parser = argparse.ArgumentParser(description='Listen to the system clipboard and write out new contents to file') parser.add_argument('filepath', nargs="?", default=default_f, help='File where clipboard contents will be written') #parser.add_argument('--clean', action='store_true', help='If Passed in, paste with no metadata') parser.add_argument( '--delim', '-d', '--postfix', '-p', dest="delim", default="\n", type=lambda x: x.decode('string_escape'), help='will be added to the end of the pasted text' ) parser.add_argument("--version", "-V", action='version', version="%(prog)s {}".format(__version__)) args = parser.parse_args() delim = args.delim last_paste_txt = pyperclip.paste() backoff = 0.15 cb_count = 0 with codecs.open(args.filepath, encoding='utf-8', mode='a') as fp: print("Hello! Pasted text will be written to {}\n".format(args.filepath)) fileno = fp.fileno() try: while True: time.sleep(backoff) paste_txt = pyperclip.paste() if paste_txt != last_paste_txt: if paste_txt and not paste_txt.isspace(): cb_count += 1 print("{}. {}".format(cb_count, paste_txt)) fp.write(paste_txt) fp.write(delim) fp.flush() os.fsync(fileno) last_paste_txt = paste_txt except KeyboardInterrupt: print("\nGoodbye! Pasted text was written to {}".format(args.filepath)) return 0
def copy_data(self, key=0): # background mode "将CVirtualGridCtrl|Custom<n>的数据复制到剪贴板,默认取当前的表格" if key: self.switch_tab(self.two_way, key) # 切换到持仓('W')、成交('E')、委托('R') print("正在等待实时数据返回,请稍候...") pyperclip.copy('') # 查到只有列表头的空白数据等3秒...orz for i in range(10): time.sleep(0.3) op.SendMessageW(reduce(op.GetDlgItem, NODE['FORM'], self.main), MSG['WM_COMMAND'], MSG['COPY_DATA'], NODE['FORM'][-1]) if len(pyperclip.paste().splitlines()) > 1: break return pyperclip.paste()
def _test_copies_columns(self): pyperclip.copy("old clipboard contents") self.page.driver.switch_to.default_content() self.page.driver.switch_to_frame( self.page.driver.find_element_by_tag_name("iframe")) self.page.find_by_xpath( "//*[@data-test='output-column-header' and " "contains(., 'some_column')]" ).click() self.page.find_by_xpath("//*[@id='btn-copy-row']").click() self.assertTrue('"Some-Name"' in pyperclip.paste()) self.assertTrue('"Some-Other-Name"' in pyperclip.paste()) self.assertTrue('"Yet-Another-Name"' in pyperclip.paste())
def check_status(bar=1,bulge=0): numFails = 0 clipboard_old = pyperclip.paste() while True: clipboard = pyperclip.paste() if (clipboard != clipboard_old): print "New ID!",clipboard clipboard_old = clipboard #Load data object for that classification # Have lookup table of the form id, bar, bulge where bar&bulge are out of 1,0 classification=read_object_classification(clipboard_old) #in the form [id,bar,bulge] #classification=['1ds4',1,0] #example of a barred galaxy withotu a bulge print "Galaxy data",classification,"Location data",bar,bulge status=bar==classification[1] and bulge==classification[2] if status: print "Success :) Do the things!" ser.write('1\n') return_code = subprocess.call(["afplay", musicFile]) ser.write('0\n') time.sleep(0.5) ser.write('M\n') time.sleep(8) ser.write('N\n') else: numFails += 1 if (numFails%5 != 0): print "Fail :( No bubbles for you" return_code = subprocess.call(["say", failText]) else: print "Fail :( No bubbles for you, but here's a Rickroll anyway..." return_code = subprocess.call(["say", rickText]) #ser.write('1\n') return_code = subprocess.call(["afplay", musicFile_rick]) #ser.write('0\n') print '-------------' time.sleep(0.5) headers={'Content-Type':'application/json','Accept':'application/vnd.api+json; version=1'}
def paste(self, evt): '''Check which panel is select and paste accordingly''' control = wx.Window.FindFocus() #which field is selected? if control == self.searchinput: #the searchbox control.SetValue(pyperclip.paste()) elif control == self.DNApy.dnaview.stc: #the main dna window self.DNApy.dnaview.paste()
def __work_loop(self): while True: time.sleep(5) if not self.default_peer: pprint("default peer is None") continue try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((self.default_peer.ip, PORT)) except Exception, e: pprint("connected to %s failed: %s" % (self.default_peer.ip, e)) sock.close() continue while True: txt = pyperclip.paste() if self.last_paste_txt != txt: pprint("clipboard changed: %s-->%s" % (self.last_paste_txt, txt)) self.last_paste_txt = txt sock.send(PROTOCOL_HEADER + txt.encode('utf-8') + '\n') continue try: sock.send(PROTOCOL_HEADER + '\n') except: pprint('connection closed by peer.') self.default_peer = None sock.close() break time.sleep(1)
def main(): if len(sys.argv) != 3: print('Usage: %s <SIP_IP> <SIP_Port>' % (sys.argv[0])) sys.exit(1) target = (sys.argv[1], int(sys.argv[2])) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(target) sock = TLSSocket(sock, client=True) tls_hello(sock) tls_client_key_exchange(sock) # Handshake Finished # Get sip packet from clipboard :D clipboard = pyperclip.paste() # Prepare SIP Plaintext packet sip = str(parse2sip(clipboard)) print(sip) sock.sendall(to_raw(TLSPlaintext(data=sip), sock.tls_ctx)) resp = sock.recvall() # Print received responses for rec in resp.fields['records']: if rec.haslayer(TLSPlaintext): print(rec.getlayer(TLSPlaintext).data)
def getField(self): # Activate IFS try: subprocess.call(['helper\ActivateIFS.exe']) except FileNotFoundError: print('Could not locate ActivateIFS.exe') # Clear the clipboard pyperclip.copy('') # Get Field ID try: subprocess.call(['helper\GetControlID.exe']) except FileNotFoundError: print('Could not locate GetControlID.exe') # Get the entry field info self.FieldID = pyperclip.paste() # Activate IFS Importer try: subprocess.call(['helper\ActivateImporter.exe']) except FileNotFoundError: print('Could not locate ActivateImporter.exe') # return the field's ID return self.FieldID
def wait_paste(conv_func): while True: value = conv_func(pyperclip.paste()) if value is not None: print('answer: %r\n\n' % value) return value time.sleep(.5)
def create_txt(self): browser = webdriver.Chrome() browser.get("http://youtubemultidownloader.com/list.php") #browser.set_window_size(10,10) if(self.quality == 1): quality_button = browser.find_element_by_id("quality1").click() elif(self.quality == 2): quality_button = browser.find_element_by_id("quality2").click() elif(self.quality == 3): quality_button = browser.find_element_by_id("quality3").click() elif(self.quality == 4): quality_button = browser.find_element_by_id("quality4").click() elif(self.quality == 5): quality_button = browser.find_element_by_id("quality5").click() elif(self.quality == 6): quality_button = browser.find_element_by_id("quality6").click() browser.refresh() playlist_url_field = browser.find_element_by_id("txtPlaylist") playlist_url_field.send_keys(Keys.CONTROL,'v') link_area = browser.find_element_by_id("txtDownload") time.sleep(60) link_area.send_keys(Keys.CONTROL,'a') link_area.send_keys(Keys.CONTROL,'c') link = pyperclip.paste() self.playlist_file.write(link) self.playlist_file.close() print 'File Created Successfully' browser.quit()
def _shift_resizes_rectangular_selection(self): pyperclip.copy("old clipboard contents") top_left_cell = self.page.find_by_xpath( "//div[contains(@class, 'slick-cell') and " "contains(., 'Some-Other-Name')]" ) initial_bottom_right_cell = self.page.find_by_xpath( "//div[contains(@class, 'slick-cell') and contains(., '14')]") ActionChains( self.page.driver ).click_and_hold(top_left_cell).move_to_element( initial_bottom_right_cell ).release(initial_bottom_right_cell).perform() ActionChains(self.page.driver).key_down(Keys.SHIFT).send_keys( Keys.ARROW_RIGHT ).key_up(Keys.SHIFT).perform() ActionChains(self.page.driver).key_down( Keys.CONTROL ).send_keys('c').key_up(Keys.CONTROL).perform() self.assertEqual("""\"Some-Other-Name"\t"22"\t"some other info" "Yet-Another-Name"\t"14"\t"cool info\"""", pyperclip.paste())
def checkData(self, rowNum, IDTag): # Iterate though all selected data entry columns for columnName, propertyDict in ColumnSelection.columnsToImportDict.items(): # Get value of IFS control pyperclip.copy(propertyDict[1]) try: subprocess.call(['helper\GetControlValue.exe']) except FileNotFoundError: print('Could not locate GetControlValue.exe') # Store text in IFS control controlText = str(pyperclip.paste()) # Get value of current cell curCell = FileSelection.sheet.cell(row=rowNum, column=column_index_from_string(columnName)) excelText = str(curCell.value) # Compare values for non blank cells if excelText != None: if controlText == excelText: # print(IDTag + ' checked. PASS' ### Debugging ### pass # Data does not match else: if IDTag not in ColumnSelection.mismatchList: ColumnSelection.mismatchList.append(IDTag) # print('Excel IFS mismatch') ### Debugging ### else: pass
def _inlet(): '''Reads all, returns content in bytes.''' content_path = None try: if args.content: content_path = args.content ## Optional clipboard feature. Requires xclip elif args.Xclip: if not pyperclip: exit('e: missing python-pyperclip') if not args.force: print('plaster your clipboard for all to see?') exit('add -f') content = bytes(pyperclip.paste(), 'utf-8') ## measures no arguments or options. elif isatty(0): print('enter a file to plaster') content_path = input('$ ') ## OK for now else: content = stdin.buffer.read() if content_path is not None: with open(content_path, 'rb') as i: content = i.read() return content except KeyboardInterrupt: print() exit('for help, try: plaster -h') except Exception as e: print('e: inlet:', e) exit(1)
copy(657) copy(695) copy(725) copy(755) if pyautogui.prompt('top or bottom team?') == 'top': top() else: bottom() try: default = 0.1 #name = pyperclip.paste() steamURL = pyperclip.paste() nameArray = [] for x in range(len(urlArray)): res = requests.get(urlArray[x]) res.raise_for_status() userProfile = bs4.BeautifulSoup(res.text, "html.parser") user = userProfile.select('.actual_persona_name') name = user[0].getText().strip() nameArray.append(name) for z in range(len(urlArray)): res = requests.get(urlArray[z]) res.raise_for_status() userProfile = bs4.BeautifulSoup(res.text, "html.parser")
import sys import webbrowser import pyperclip usage = """\ gt [destination_language] [word_or_sentence] opens google translate in browser with the desired parameters (press enter to exit) """ available_languages = {'en': 'english', 'fr': 'french'} try: dest_lang = sys.argv[1] word = sys.argv[2] except IndexError: input(usage) try: lang = available_languages[dest_lang] except KeyError: input('Unavailable language : {} (enter to exit) '.format(dest_lang)) if len(sys.argv) > 2: word = ' '.join(sys.argv[2:]) else: word = pyperclip.paste() webbrowser.open('https://www.google.ca/search?q=translate+to+' + lang + '=' + word)
# -*- coding: utf-8 -*- """ Created on Fri Dec 4 23:05:14 2020 @author: kbasa """ import pyperclip p_in = pyperclip.paste().splitlines() # %% Part 1 def nice(string): valid = 0 count_w = 0 for w in "aeiou": count_w += string.count(w) if count_w >= 3: valid += 1 for i in range(1, len(string)): if string[i - 1] == string[i]: valid += 2 break if not any([(bad in string) for bad in ["ab", "cd", "pq", "xy"]]): valid += 4 return valid == 8 - 1
import pyperclip import webbrowser import sys if len(sys.argv) < 2: url = pyperclip.paste() url = url.split(' ') else: url = sys.argv[1:] gUrl = "https://www.google.com/maps/search/" for item in url: gUrl = gUrl + "+" + item webbrowser.open(gUrl)
# py.exe mcb.pyw <keyword> - Loads keyword to clipboard # py.exe mcb.pyw list - loads all keywords to clipboard # py.exe mcb.pyw delete <keyword> - Deletes keyword from shelve # py.exe mcb.pyw deleteall - Deletes all keywords from shelve # py.exe mcb.pyw printall - Creates a list of all values onto the clipboard # py.exe mcb.pyw addto - Creates list of items to add to printall list import shelve import pyperclip import sys mcb_shelf = shelve.open('mcb') # Save clipboard content if len(sys.argv) == 3 and sys.argv[1].lower() == 'save': mcb_shelf[sys.argv[2]] = pyperclip.paste() elif len(sys.argv) == 3 and sys.argv[1].lower() == 'delete': del mcb_shelf[sys.argv[2]] elif len(sys.argv) == 2: # List keywords and load content if sys.argv[1].lower() == 'list': pyperclip.copy(str(list(mcb_shelf.keys()))) elif sys.argv[1].lower() == 'deleteall': for keyword in list(mcb_shelf.keys()): del mcb_shelf[keyword] elif sys.argv[1].lower() == 'printall': value_list = [] for key, value in list(mcb_shelf.items()): value = value.strip() value_list.append(value) pyperclip.copy(str(value_list))
continuarsiseencuentra(numero) os.chdir("%s" % diractual) time.sleep(0.3) pg.press('down') time.sleep(0.5) pg.hotkey('shift', 'f10') time.sleep(0.5) pg.press('down') time.sleep(0.5) pg.press('enter') time.sleep(0.05) pg.hotkey('ctrl', 'l') time.sleep(0.4) pg.hotkey('ctrl', 'c') time.sleep(0.4) link2.append(pc.paste()) if len(link2) == 1: x = "No había anterior" elif (link2[j] == link2[j - 1]) & (len(link2) != 1): x = "Sí, hay que revisar esto" else: x = "No, está bien :D" print("Hay " + str(len(link2)) + " links2 guardados ¿es igual al último? %s" % x) # browser.switch_to.window(browser.window_handles[1]) # link2.append(browser.current_url) print("Se encontró el link2 %s/" % (j + 1) + "%s " % (len(link)) + ("(%s%%)") % (round((j + 1) * 100 / (len(link)), 2))) pg.hotkey('ctrl', 'w') # browser.switch_to.window(browser.window_handles[0]) time.sleep(1.5)
def get_system_text(cls): return pyperclip.paste()
def format(replacements, form): clip = pyperclip.paste() for old in replacements: clip = clip.replace(old, replacements[old]) pyperclip.copy(form(clip))
#! python3 #mapIt.py - opens google maps and copies addres from clipboard to maps import webbrowser, sys, pyperclip if len(sys.argv) > 1: # Get address from command line address = ' '.join(sys.argv[1]) else: # Get address from clipboard address = pyperclip.paste() webbrowser.open('https://www.google.com/maps/place/' + address)
(\d{4}) # last 4 digits (\s*(ext|x|ext.)\s*(\d{2,5}))? # extension )''', re.VERBOSE) # Create email regex. emailRegex = re.compile(r'''( [a-zA-Z0-9._%+-]+ # username @ # separator [a-zA-Z0-9.-]+ # domain name (\.[a-zA-Z]{2,4}) # top-level domain )''', re.VERBOSE) # Find matches in clipboard text. text = str(pyperclip.paste()) matches = [] for groups in phoneRegex.findall(text): phoneNum = '-'.join([groups[1], groups[3], groups[5]]) if groups[8] != '': phoneNum += ' x' + groups[8] matches.append(phoneNum) for groups in emailRegex.findall(text): matches.append(groups[0]) # Copy results to the clipboard. if len(matches) > 0: pyperclip.copy('\n'.join(matches))
import webbrowser, sys, pyperclip, requests, bs4 if len(sys.argv) > 1: term = ' '.join(sys.argv[1:]) else: term = pyperclip.paste() headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36' } URL = 'https://www.google.co.in/search?q=' + term res = requests.get(URL, headers=headers) try: res.raise_for_status() except Exception as ex: print('There was a problem: %s' % (ex), '\nSorry!!') soup = bs4.BeautifulSoup(res.text, "html.parser") card = soup.select('g-inner-card') cardNum = len(card) if cardNum == 0: print("There is no news about %s.Try something else." % (term)) sys.exit(0) f = '.' + ''.join(card[0].attrs.get('class')) + ' a'
#! python3 import os import pprint import pyperclip grid = [['.', '.', '.', '.', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['O', 'O', 'O', 'O', 'O', '.'], ['.', 'O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['.', '.', '.', '.', '.', '.']] for i in range(len(grid)): for j in range(len(grid[i])): print(grid[j][i], end='') print() def char2grid(string): lists = string.split(os.linesep) finalList = [] for x in range(len(lists)): finalList.append(list(lists[x])) return finalList pprint.pprint(char2grid(pyperclip.paste())) for i in range(len(char2grid(pyperclip.paste()))): for j in range(len(grid[i])): print(grid[j][i], end='') print()
os.makedirs(target_dir) filenames = glob('{}/*.[jp]*'.format(source_dir)) # print(','.join(filenames)) strFileNames = '' for i, filename in enumerate(filenames): # 拼接文件名字符串 strFileNames = strFileNames + '"' + filename + '",' filesize = os.path.getsize(filename) output_filename = filename.replace(source_dir, target_dir) # output_filename = time.strftime("%Y-%m-%d", time.localtime()) + '000' + str(i) + '.png'; print('output_filename:', output_filename) if filesize >= threshold: print(filename) with Image.open(filename) as im: width, height = im.size new_width = width // 2 new_height = int(new_width * height * 1.0 / width) print('adjusted size:', new_width, new_height) resized_im = im.resize((new_width, new_height)) resized_im.save(output_filename) else: with Image.open(filename) as im: im.save(output_filename) # 字符串复制到剪切板 strFileNames = strFileNames.replace(source_dir + '\\', './' + target_dir + '/') print(strFileNames[0:-1]) pyperclip.copy(strFileNames[0:-1]) spam = pyperclip.paste()
#!/usr/bin/python3 # Add '>' to the beginning of each line of text on the clipboard # For convenience when using 4chan import pyperclip # Get the text from the clipboard text = pyperclip.paste() # Turn it into green text lines = text.split('\n') for i in range(len(lines)): lines[i] = '>' + lines[i] # Print to clipboard and give appropriate message when completed text = '\n'.join(lines) pyperclip.copy(text) print('Text on clipboard has been converted to green text')
#! Python 3 # Find the first ten digits of the sum of the following one-hundred 50-digit numbers import pyperclip print( "Please input the number you would like to find the greatest product of 13 adjacent digits:" ) input() Values = list(map(int, pyperclip.paste().split('\r\n'))) SumTotal = sum(Values) print(str(SumTotal)[0:10])
def add_to_clipster(): buffer.append(pyperclip.paste()) print(buffer) return
def logistic_window_loop(display_main): #overall variables close_window = False algo_selected = 'lbfgs' pressed = True #execution variables q = 0 val = 0 start_clock = 0.0 end_clock = 0.0 time_updated = False score_updated = False input_active = '' freeze = False while not close_window: q += 1 #print('threads', threading.enumerate()) if threading.activeCount() == 1 and freeze: freeze = False end_clock = time.time() for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit quit() elif event.type == pygame.MOUSEBUTTONUP: pressed = True elif event.type == pygame.KEYDOWN: if input_active: if input_active == 'alpha': temp = window_data['learning_rate_p_prop'][ 'inner_rect_prop']['msg'] elif input_active == 'lambda': temp = window_data['regularize_para_p_prop'][ 'inner_rect_prop']['msg'] elif input_active == 'epocs_count': temp = window_data['epocs_para_p_prop'][ 'inner_rect_prop']['msg'] elif input_active == 'predict_path': temp = window_data['predicted_input_path'][ 'inner_rect_prop']['msg'] elif input_active == 'file_name': temp = window_data['outputfile_name'][ 'inner_rect_prop']['msg'] if event.key == pygame.K_RETURN: input_active = '' elif event.key == pygame.K_BACKSPACE: temp = temp[:-1] elif event.key == pygame.K_v: mods = pygame.key.get_mods() if mods & pygame.KMOD_CTRL: copied = True temp = pyperclip.paste() else: temp += event.unicode else: temp += event.unicode if input_active == 'alpha': window_data['learning_rate_p_prop']['inner_rect_prop'][ 'msg'] = temp elif input_active == 'lambda': window_data['regularize_para_p_prop']['inner_rect_prop'][ 'msg'] = temp elif input_active == 'epocs_count': window_data['epocs_para_p_prop']['inner_rect_prop'][ 'msg'] = temp elif input_active == 'predict_path': window_data['predicted_input_path']['inner_rect_prop'][ 'msg'] = temp elif input_active == 'file_name': window_data['outputfile_name']['inner_rect_prop'][ 'msg'] = temp if not freeze: display_main.fill(window_data['background_color']) #Main Tools #DataSet Size window_data['data_set_size_rec_prop']['msg'] = ' m- ' + str( window_data['data_set']['X'].shape[0]) data_set_size_rec = sp.button(window_data['data_set_size_rec_prop']) data_set_size_rec.draw(display_main, clickable=False, dont_change=True) #Features Count window_data['features_rec_prop']['msg'] = 'n- ' + str( window_data['data_set']['X'].shape[1]) features_rec = sp.button(window_data['features_rec_prop']) features_rec.draw(display_main, clickable=False, dont_change=True) #Class Count window_data['classes_rec_prop']['msg'] = 'Classes - ' + str( len(set(window_data['data_set']['y']))) features_rec = sp.button(window_data['classes_rec_prop']) features_rec.draw(display_main, clickable=False, dont_change=True) #learing button learning_b = sp.button(window_data['learning_b_prop'], shape='circle') window_data['learning_b_prop']['pressed'] = learning_b.draw( display_main, clickable=True, freeze=freeze) if window_data['learning_b_prop']['pressed'] and not freeze and pressed: freeze = True window_data['fun_completed'] = False start_clock = time.time() val = 0 #make a thread for the final function compute_thread = thread(name='Compute_thread', fun=compute) #threads.append(compute_thread) compute_thread.setDaemon(True) compute_thread.start() time_updated = False total_cost_updated = False window_data['time']['inner']['inner_msg'] = 'Time Elapsed : ' window_data['score']['inner']['inner_msg'] = 'Score : ' #solver if algo_selected == 'lbfgs': window_data['algo_rec_prop']['msg'] = 'lbfgs' elif algo_selected == 'liblinear': window_data['algo_rec_prop']['msg'] = 'liblinear' elif algo_selected == 'sag': window_data['algo_rec_prop']['msg'] = 'sag' elif algo_selected == 'saga': window_data['algo_rec_prop']['msg'] = 'saga' elif algo_selected == 'newton-cg': window_data['algo_rec_prop']['msg'] = 'newton-cg' algo_rec = sp.button(window_data['algo_rec_prop']) window_data['algo_rec_prop']['pressed'] = algo_rec.draw(display_main, clickable=True, freeze=freeze) if window_data['algo_rec_prop']['pressed'] and pressed and not freeze: if algo_selected == 'lbfgs': algo_selected = 'liblinear' elif algo_selected == 'liblinear': algo_selected = 'sag' elif algo_selected == 'sag': algo_selected = 'saga' elif algo_selected == 'saga': algo_selected = 'newton-cg' elif algo_selected == 'newton-cg': algo_selected = 'lbfgs' pressed = False #Regularize Parameter Prompt Regularize_rate_ = sp.rect_new( window_data['regularize_para_p_prop']['outer_rect_prop'], type='shadow') Regularize_rate_box = Regularize_rate_.draw(display_main) lambda_desc = sp.message( window_data['regularize_para_p_prop']['lambda_text'], window_data['regularize_para_p_prop']['lambda_text_prop'], text_font) lambda_desc_box = lambda_desc.message_display(display_main) Regularize_rate_b = sp.button( window_data['regularize_para_p_prop']['inner_rect_prop']) window_data['regularize_para_p_prop']['inner_rect_prop'][ 'pressed'] = Regularize_rate_b.draw(display_main, clickable=True, dont_change=True) if window_data['regularize_para_p_prop']['inner_rect_prop'][ 'pressed'] and not freeze: input_active = 'lambda' window_data['regularize_para_p_prop']['inner_rect_prop'][ 'msg'] = '' #Epocs Count epocs_count = sp.rect_new( window_data['epocs_para_p_prop']['outer_rect_prop'], type='shadow') epocs_count_box = epocs_count.draw(display_main) epocs_desc = sp.message( window_data['epocs_para_p_prop']['epocs_text'], window_data['epocs_para_p_prop']['epocs_text_prop'], text_font) epocs_desc_box = epocs_desc.message_display(display_main) epocs_count_b = sp.button( window_data['epocs_para_p_prop']['inner_rect_prop']) window_data['epocs_para_p_prop']['inner_rect_prop'][ 'pressed'] = epocs_count_b.draw(display_main, clickable=True, dont_change=True) if window_data['epocs_para_p_prop']['inner_rect_prop'][ 'pressed'] and not freeze: input_active = 'epocs_count' window_data['epocs_para_p_prop']['inner_rect_prop']['msg'] = '' ############################################################################################################################################################################################### #Learning Process Fileds #Progress Bar progress_desc = sp.message( window_data['progress_bar']['text']['text_msg'], window_data['progress_bar']['text']['text_prop']) progress_box = progress_desc.message_display(display_main) progress_bar_ = sp.rect_new( window_data['progress_bar']['progress_bar_prop'], type='progress') if q % 40 == 0 and val < 100 and freeze: val += 1 if window_data['fun_completed']: val = 100 progress_bar_box = progress_bar_.draw(display_main, val) pygame.draw.rect(display_main, (10, 10, 10), (600, 145, 55, 50)) window_data['progress_bar']['percent']['percent_msg'] = str(val) + '%' progress_percent_desc = sp.message( window_data['progress_bar']['percent']['percent_msg'], window_data['progress_bar']['percent']['percent_prop']) progress_percent_box = progress_percent_desc.message_display( display_main) #Score score_ = sp.rect_new(window_data['score']['outer_rect'], type='normal') score_box = score_.draw(display_main) if not score_updated: window_data['score']['inner']['inner_msg'] = window_data['score'][ 'inner']['inner_msg'] + str(round(end_clock - start_clock, 2)) score_updated = True score_msg = sp.message(window_data['score']['inner']['inner_msg'], window_data['score']['inner']['inner_prop']) score_msg_box = score_msg.message_display(display_main) #time elapsed time_ = sp.rect_new(window_data['time']['outer_rect'], type='normal') time_box = time_.draw(display_main) if not time_updated and not freeze: window_data['time']['inner'][ 'inner_msg'] = window_data['time']['inner']['inner_msg'] + str( round(end_clock - start_clock, 2)) + ' seconds' time_updated = True time_msg = sp.message(window_data['time']['inner']['inner_msg'], window_data['time']['inner']['inner_prop']) time_msg_box = time_msg.message_display(display_main) ############################################################################################################################################################################################### #Predicted Fields #Input File Path input_path_ = sp.message( window_data['predicted_input_path']['text']['text_msg'], window_data['predicted_input_path']['text']['text_prop']) input_path_box = input_path_.message_display(display_main) p_input_ = sp.rect_new( window_data['predicted_input_path']['outer_rect'], type='normal') p_input_box = p_input_.draw(display_main) input_path_inner = sp.button( window_data['predicted_input_path']['inner_rect_prop']) window_data['predicted_input_path']['inner_rect_prop'][ 'pressed'] = input_path_inner.draw(display_main, clickable=True, dont_change=True) if window_data['predicted_input_path']['inner_rect_prop'][ 'pressed'] and not freeze and window_data[ 'Computation_status'] == 'Done': input_active = 'predict_path' window_data['predicted_input_path']['inner_rect_prop']['msg'] = '' #Name of Outupt file o_input_ = sp.rect_new(window_data['outputfile_name']['outer_rect'], type='normal') o_input_box = o_input_.draw(display_main) outputfile_inner = sp.button( window_data['outputfile_name']['inner_rect_prop']) window_data['outputfile_name']['inner_rect_prop'][ 'pressed'] = outputfile_inner.draw(display_main, clickable=True, dont_change=True) if window_data['outputfile_name']['inner_rect_prop'][ 'pressed'] and not freeze and window_data[ 'Computation_status'] == 'Done': input_active = 'file_name' window_data['outputfile_name']['inner_rect_prop']['msg'] = '' #Predict Button predict_b = sp.button(window_data['predict_b_prop'], shape='rect') window_data['predict_b_prop']['pressed'] = predict_b.draw( display_main, clickable=True, dont_change=False, freeze=freeze) if window_data['predict_b_prop'][ 'pressed'] and not freeze and window_data[ 'Computation_status'] == 'Done': predict_thread = thread(name='predict', fun=predict_fun) predict_thread.start() window_data['fun_completed'] = False val = 0 freeze = True ############################################################################################################################################################################################### #status Bar status_bar_ = sp.rect_new(window_data['status_bar']['outer_rect'], type='normal') mean_sqr_box = status_bar_.draw(display_main) status_bar_msg = sp.message( window_data['status_bar']['inner']['inner_msg'], window_data['status_bar']['inner']['inner_prop']) status_bar_msg_box = status_bar_msg.message_display(display_main) status_msg = sp.message( window_data['status_bar']['inner']['inner_msg1'], window_data['status_bar']['inner']['inner_prop1']) status_msg_box = status_msg.message_display(display_main) ############################################################################################################################################################################################### forward_b = sp.button(window_data['forward_button'], shape='rect') window_data['forward_button']['pressed'] = forward_b.draw( display_main, clickable=True, freeze=freeze) if window_data['forward_button']['pressed'] and not freeze and pressed: nn.neural_window_start() #print('input_active = ', input_active) pygame.display.update() clock.tick(60)
# check if path is a text file if ".txt" in os.path.basename(path): # read file file = open(os.path.abspath(path)) content = file.read() # close file file.close() key = sys.argv[3] mcbShelf[key] = content else: print("Path should lead to a text file") else: print("Path does not exist") # TODO: Save clipboard content elif len(sys.argv) == 3 and sys.argv[1].lower() == "save": content = pyperclip.paste() #copies the clipboard content mcbShelf[sys.argv[2]] = content #stores the content to the keyword in the shelf object # TODO : List keywords and load content elif len(sys.argv) == 2: keys = list(mcbShelf.keys()) if sys.argv[1].lower() == "list": content = "" for pos in range(len(keys)): content += "{}. ".format(pos) + keys[pos] + "\n" # content += mcbShelf[key] + "\n"*2 # content += "-"*20 + "\n"*2 pyperclip.copy(content) print(content) else: # TODO: Load keyword to clipboard if sys.argv[1] in keys:
import pyperclip def isPhoneNumber(text): if len(text) != 12: return False for i in range(0, 3): if not text[i].isdecimal(): return False if text[3] != "-": return False for i in range(4, 7): if not text[i].isdecimal(): return False if text[7] != '-': return False for i in range(8, 12): if not text[i].isdecimal(): return False return True message = pyperclip.paste() for i in range(len(message)): chunk = message[i:i + 12] if isPhoneNumber(chunk): print('Znaleziono numer telefonu: ' + chunk) print('Gotowe!')
import pyperclip pyperclip.copy('Pyperclip copies to and pastes from the clipboard.') pyperclip.paste()
def on_activate_strip(): time.sleep(0.2) # Delay to avoid occasional empty copy buffer data = pyperclip.paste() text = data.strip() pyperclip.copy(text)
# -*- coding: utf-8 -*- import pyperclip data = pyperclip.paste() print(data.encode('utf-8')) data = data.replace(u' TMs/HMs\r\n\r\n Move\r\n\r\n ', '') data = data.replace(u'\r\n\r\n Bold indicates this Pokémon receives STAB from this move.Italic indicates an evolved or alternate form of this Pokémon receives STAB from this move.\r\n', '') data = data.replace(u'\r\n\r\n ', ';') print(data.encode('utf-8')) pyperclip.copy(data)
import pyperclip, requests, json shuru = pyperclip.paste() url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule' data = { 'i': shuru, 'from': 'AUTO', 'to': 'AUTO', 'smartresult': 'dict', 'client': 'fanyideskweb', 'salt': '15445136920078', 'sign': '5243255304e7f840eb331ffb854e2be1', 'ts': '1544513692007', 'bv': 'b33a2f3f9d09bde064c9275bcb33d94e', 'doctype': 'json', 'version': '2.1', 'keyfrom': 'fanyi.web', 'action': 'FY_BY_REALTIME', 'typoResult': 'false' } r = requests.get(url, data) a = json.loads(r.text) print(a['translateResult'][0][0]['tgt']) pyperclip.copy(a['translateResult'][0][0]['tgt']) input('翻译结果已复制至剪切板,点击enter退出')
#A simple program to search address in Google Maps from clip board or from command line import webbrowser, sys, pyperclip if len(sys.argv ) > 1: #checks if Address passed as an argument from command prompt address = ' '.join(sys.argv[1:]) else: address = pyperclip.paste() #Address is taken from clipboard webbrowser.open('https://www.google.com/maps/place/' + address)
def say_it(): word = pyperclip.paste() # paste text from clipboard engine.say(word) # say pasted text engine.runAndWait( ) # blocks while processing all currently queued commands
#! Python 3 # Find the difference between the sum of the squares in a range and the square of the sum of the range import pyperclip print( "Please input the number you would like to find the greatest product of 13 adjacent digits:" ) InputNum = ''.join(pyperclip.paste().split()) InputLen = len(InputNum) MaxProduct = 0 for i in range(InputLen - 12): Product = 1 for j in range(13): Product *= int(InputNum[i + j]) if Product > MaxProduct: MaxProduct = Product print(MaxProduct)
# Author : Shivam Chauhan # Date : March 6, 2019 # This programs adds bullets(wiki) to the copied text on clipboard and # copies back the formatted text to the clipboard again import pyperclip text = pyperclip.paste() # Store copied code from clipboard lines = text.split("\n") for index in range(len(lines)): lines[index] = "* " + lines[index].strip() text = "\n".join(lines) pyperclip.copy(text)
def Do(): if start: #主代码--------------- # maxTime = 3#3秒复制 调用copy() 不管结果对错 # while (maxTime > 0): # maxTime = maxTime - 0.5 # time.sleep(0.5) # #print('doing') # copy() # # targetName=pyperclip.paste() targetName=getCopy() dataResult=getresult(pyperclip.paste()) if (dataResult.result == ''): print('没有这个:' + pyperclip.paste() + ' ,需更新表格') # 没有找到这个 跳过 to do --------------------- tapkey(k.escape_key) tapkey(k.down_key) tapkey(k.left_key) tapkey(k.enter_key) return else: if(dataResult.typeArray==''): print('无规格直接输入') tapkey(k.enter_key, 5) k.type_string(dataResult.result) tapkey(k.enter_key) time.sleep(5) tapkey(k.escape_key) tapkey(k.left_key, 11)#适当修改 tapkey(k.enter_key,3)#适当修改 else: print('表格匹配名字,判断且有规格') tapkey(k.enter_key) maxTime = 3 while (maxTime > 0): maxTime = maxTime - 0.5 time.sleep(0.5) #print('doing') copy() targetType = pyperclip.paste() if(targetType==targetName):#相等则targetType为空 规格型号没填 复制为上次结果 targetType='' result_2 = getresult_2(targetName, targetType) if(result_2==''): print('无匹配 '+targetName+' 无匹配 '+targetType) tapkey(k.escape_key) tapkey(k.down_key) tapkey(k.left_key,2) tapkey(k.enter_key) else: print('规格匹配输入'+targetName+' '+targetType) tapkey(k.enter_key,4)#适当修改 k.type_string(result_2) tapkey(k.enter_key) time.sleep(5) tapkey(k.escape_key) tapkey(k.left_key, 11)#适当修改 tapkey(k.enter_key,3)#适当修改 #判断型号 TODO--------------------- return
print(s.startswith("Bob")) print(s.endswith("D")) s = "hello" #' l.rjust(10)是说我们希望右对齐,将'Hello'放在一个长度为 10 的字符串中。 # 'Hello'有 5 个字符, 所以左边会加上 5 个空格, 得到一个 10 个字符的字符串, 实现 # 'Hello'右对齐。 print(s.rjust(10)) print(s.rjust(10, "*")) print(s.center(11, "-")) def printPicnic(itemsDict, leftWidth, rightWidth): print('PICNIC ITEMS'.center(leftWidth + rightWidth, '-')) for k, v in itemsDict.items(): print(k.ljust(leftWidth, '.') + str(v).rjust(rightWidth)) picnicItems = {'sandwiches': 4, 'apples': 12, 'cups': 4, 'cookies': 8000} printPicnic(picnicItems, 12, 5) printPicnic(picnicItems, 20, 6) t = "hello" print(t.rstrip("hoe")) # pyperclip import pyperclip # s = "yunxifeng" # print(pyperclip.copy(s)) ss = pyperclip.paste() print(ss)
print('Hello.istitle():', 'Hello'.istitle()) print("'hello123'.isalpha():", 'hello123'.isalpha()) # 是否只有字母且不为空 print("'hello123'.isalnum():", 'hello123'.isalnum()) # 是否只有字母和数字且不为空 print("'hello123'.isdecimal():", 'hello123'.isdecimal()) # 是否只有数字且不为空 print("' '.isspace():", ' '.isspace()) # 是否只有空格且不为空 # ljust() rjust() center(a,b) 填充文本 # 第一个参数占位大小;第二个参数填充字符,默认是空格 print("\nljust() rjust() center() 填充文本") print("'hello'.rjust(20):", 'hello'.rjust(20)) print("'hello'.ljust(20):", 'hello'.ljust(20)) print("'hello'.center(20):", 'hello'.center(20)) print("'hello'.rjust(20,'*'):", 'hello'.rjust(20, '*')) print("'hello'.ljust(20,'-'):", 'hello'.ljust(20, '-')) print("'hello'.center(20,'_'):", 'hello'.center(20, '_')) # strip print("\nstrip去空格") string2 = " hello world. " print("string2:", string2) print("string2.rstrip():", string2.rstrip()) print("string2.lstrip():", string2.lstrip()) print("string2.strip():", string2.strip()) # pyperclip copy() paste()可以向计算机剪贴板发送接受文本 print("\npyperclip") import pyperclip pyperclip.copy("hel0000") # 修改剪贴板 str = pyperclip.paste() # 返回剪贴板内容 print(str)