Python 2.7 pyperclip loop - python-2.7

this is the current code:
import time
import sys
import os
sys.path.append(os.path.abspath("SO_site-packages"))
import pyperclip
recent_value = ""
while True:
tmp_value = pyperclip.paste()
if not tmp_value = recent_value:
recent_value = tmp_value
print("Value changed: %s" % str(recent_value)[:20])
time.sleep(0.1)
What I'm trying to do: create a constant loop that waits for a user to copy text to clipboard, and print it whenever that happens.
What happens currently: It only prints out the last copied item and stops.
My question is: How to make this code a listening loop?
Help will be deeply appreciated.

Related

How to end animation after function completes

I am writing a simple program to keep an eye on a few Addresses.
I want a simple text cursor animation to run while the program does its thing. I've managed to do that. However, my problem is that after the function doing the scanning finishes the animation keeps going and won't stop until I hit the break key.
import os
import time
import sys
import itertools
import threading
hostname = [multiple site list]
def responder(hostname):
while True:
for item in hostname:
response = os.system("ping -q -c 1 -n > /dev/null 2>&1 " + item)
if response == 0:
time.sleep(2)
else:
print item, 'is DOWN!'
sys.exit()
def animate():
for c in itertools.cycle(['|', '\'']):
sys.stdout.write('\rscanning for bums > ' + c)
sys.stdout.flush()
time.sleep(0.1)
t = threading.Thread(target=animate)
t.start()
responder(hostname)
I know the code might be a little messy as I'm halfway through the project but any idea what it is I could change to make the animation stop when the responder function exits?
You need to pass a threading.Event to the animate function and set it when you want it to stop:
import os
import time
import sys
import itertools
import threading
hostname = ['bogus.org']
def responder(hostname, t, quit_flag):
while True:
for item in hostname:
response = os.system("ping -q -c 1 -n %s >> /dev/null 2>&1" % item)
if response == 0:
time.sleep(2)
else:
quit_flag.set()
t.join()
print "%s is DOWN!" % item
return
def animate(quit_flag):
for c in itertools.cycle(['|', '\'']):
if quit_flag.is_set():
print ""
break
sys.stdout.write('\rscanning for bums %s > %s' % (quit_flag.is_set(), c))
sys.stdout.flush()
time.sleep(0.1)
quit_flag = threading.Event()
t = threading.Thread(target=animate, args=(quit_flag,))
t.daemon = True
t.start()
responder(hostname, t, quit_flag)
I modified your responder function so that it sets the quit flag, joins the animate thread, prints the message, and then returns. This guarantees that the animate thread is finished before the message is printed.
I realized that trying to use a regular variable does not work because only the value gets passed to the animate function. If you do not want to use a threading.Event, you can use a single element array or some other object that will get passed by reference.

Cant make multiple copies of a file using shutil python

Following is a python code snippet I am running on my server. I want to replicate a file 'n' times and save with a different name each time. However, whatever value I give for loop I always end up getting a single replica made.
import os
import time
import shutil
os.chdir(''server_directory)
src='myFile.jpg'
numberofcopies=10
for i in range(0,numberofcopies):
print "replicating {0}".format(i+1)
timestamp=int(round(time.time()))
dst='{0}.jpg'.format(timestamp)
shutil.copy2(src, dst)
Apparently using a timeout in the main thread and running the loop infinitely unless Ctrl-C interruption solved my problem.
import os
import time
import shutil
os.chdir('server_directory')
src='file to replicate.jpg'
i=0
while True:
print "replicating {0}".format(i+1)
timestamp=int(round(time.time()))
dst='{0}.jpg'.format(timestamp)
shutil.copy2(src, dst)
i=i+1
time.sleep(1)
This should replicate my file 5 times with different names.
import os
import shutil
import os
for r in range(5):
original = r'transactions.xlsx'
target = f'Newfile{r}.xlsx'
shutil.copyfile(original, target)
print (f'Action: replicating {original} as {target}')

Fix pcap checksum using Python Scapy

I've written one small python script to fix the checksum of L3-4 protocols using scapy. When I'm running the script it is not taking command line argument or may be some other reason it is not generating the fix checksum pcap. I've verified the rdpcap() from scapy command line it is working file using script it is not getting executed. My program is
import sys
import logging
logging.getLogger("scapy").setLevel(1)
try:
from scapy.all import *
except ImportError:
import scapy
if len(sys.argv) != 3:
print "Usage:./ChecksumFixer <input_pcap_file> <output_pcap_file>"
print "Example: ./ChecksumFixer input.pcap output.pcap"
sys.exit(1)
#------------------------Command Line Argument---------------------------------------
input_file = sys.argv[1]
output_file = sys.argv[2]
#------------------------Get The layer and Fix Checksum-------------------------------
def getLayer(p):
for paktype in (scapy.IP, scapy.TCP, scapy.UDP, scapy.ICMP):
try:
p.getlayer(paktype).chksum = None
except: AttributeError
pass
return p
#-----------------------FixPcap in input file and write to output fi`enter code here`le----------------
def fixpcap():
paks = scapy.rdpcap(input_file)
fc = map(getLayer, paks)
scapy.wrpcap(output_file, fc)
The reason your function is not executed is that you're not invoking it. Adding a call to fixpcap() at the end of your script shall fix this issue.
Furthermore, here are a few more corrections & suggestions:
The statement following except Exception: should be indented as well, as follows:
try:
from scapy.all import *
except ImportError:
import scapy
Use argparse to parse command-line arguments.
Wrap your main code in a if __name__ == '__main__': block.

Rapid Gui with Qt and Python Chaper4 Alert.pyw Not Popping

i'm starting to learn Qt and i'm currently doing the alert.pyw example. The example works just fine but i wanted to test it if it really works like it's described so when i pass the time parameter i acctually put in a time to be reached (for example, now it's 11:34 and i passed 11:35 or 11:36, just to be sure i tried a few times with longer waiting times and i actually waited after time it should have popped up for a few minutes).
Well, when the set time is reachead no window actually pop up to "Wake me up".
Is this because the code actually isn't meant to work or there is something weird going on?
Here is the code:
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from future_builtins import *
import sys
import time
from PyQt4.QtCore import (QTime, QTimer, Qt, SIGNAL)
from PyQt4.QtGui import (QApplication, QLabel)
app = QApplication(sys.argv)
try:
due = QTime.currentTime()
message = "Alert!"
if len(sys.argv) < 2:
raise ValueError
hours, mins = sys.argv[1].split(":")
due = QTime(int(hours), int(mins))
if not due.isValid():
raise ValueError
if len(sys.argv) > 2:
message = " ".join(sys.argv[2:])
except ValueError:
message = "Usage: alert.pyw HH:MM [optional message]" # 24hr clock
while QTime.currentTime() < due:
time.sleep(20) # 20 seconds
label = QLabel("<font color=red size=72><b>{0}</b></font>"
.format(message))
label.setWindowFlags(Qt.SplashScreen)
label.show()
QTimer.singleShot(60000, app.quit) # 1 minute
app.exec_()
Thanks for any help

python 2.7 while loop, ttk.progressbar not working

I am working on a progress bar that keeps track of a certain function in pygame.
The following code causes a loop that I must force quit. And I can not figure our my error. Any help would be great.
from Tkinter import *
import ttk
import sys
import pygame
myGui = Tk()
myGui.title("Progress Bar")
myGui.geometry("400x200+200+300")
value_progress = StringVar()
pygame.mixer.init()
pygame.mixer.music.load("/home/david/Documents/aaa.mp3")
pygame.mixer.music.play()
def position():
global value_progress
while pygame.mixer.music.get_busy() == True:
value_progress.set(float(pygame.mixer.music.get_pos()))
b = Button(myGui, text="Start", )
b.pack()
p = ttk.Progressbar(myGui, variable=value_progress,
mode='determinate', length=350,
maximum= 512920)
p.pack()
I call the function from the shell. and then it stalls and does not come out of it.
This is only the progress bar portion of my work. However, it causes the program to crash every time.
Do not loop. Instead try following code:
def position():
global value_progress
if pygame.mixer.music.get_busy():
value_progress.set(float(pygame.mixer.music.get_pos()))
myGui.after(100, position)
Tk.after(ms, f) call f after specified ms millisecond.