How to copy a file to clipboard in python - python

Like normally, we can copy files directly to clipboard by simply
ctrl + c
But I want to do that using python
path = "..."
def copy_file_to_clipboard() -> None:
clipboard.copy_file(path) # this is a false code, but I want to know the code to do so

here is a solution tested in python 3.9 (Notebook jupyter) :
import pyperclip as pc
def copy_to_clipboard(file_name):
with open(file_name, 'r') as f:
text = f.read()
pc.copy(text)
print("File successfully copied to clipboard!")
copy_to_clipboard('file.txt')

Related

how can i update a python file by comparing it to a file hosted on my rasbery pi?

I am attempting to make a program update itself to the newest version that I have made. E.g. I added a new functionality to it. It would be useful for me to be able to upload the updated file to a central location like my Raspberry Pi and have the program update itself across all of my computers without updating each one individually.
I have made the bellow code, but it does not work. It can recognize when the file is up-to-date but running the new program it downloads fails, it successfully downloads and deletes itself, but the new program is not run, with no error messages being shown.
Update test.py:
#updaterV1.py
import time
import requests
import os
import hashlib
time.sleep(5)
cwd = os.getcwd()
URL = r"http://[rasberry pi's ip]/update%20files/dev/hash.txt"
hash_path = os.path.join(cwd,"remote hash.txt")
with open (hash_path, "wb") as f:
f.write(requests.get(URL).content)
with open(hash_path,"r") as hash_file:
remotehash = (hash_file.readline()).strip()
os.remove(hash_path)
hasher = hashlib.sha256()
with open(__file__, 'rb') as self_file:
selfunhashed = self_file.read()
hasher.update(selfunhashed)
selfhash = hasher.hexdigest()
print(selfhash)
print(remotehash)
if (selfhash == remotehash):
print("program is up to date")
input()
else:
update_path = os.path.join(cwd,"temp name update.py")
URL = r"http://[rasberry pi's ip]/update%20files/dev/update.py"
with open (update_path, "wb") as f:
f.write(requests.get(URL).content)
with open(update_path,"r") as f:
name = f.readline().strip()
name = name[1:] #use the 1st line as "#name.py" not "# name"
update_path = os.path.join(cwd,name)
try:
os.remove(update_path)
except:
pass
os.rename(os.path.join(cwd,"temp name update.py"),update_path)
os.system("python \""+update_path+"\"")
print("removing self file now")
os.remove(__file__)
It uses a separate TXT file with the hash of the program stored in the same folder to check the remote files hash without downloading the actual file to hash it locally.

How to use python to create url shortcut on mac?

There are answers to the window version. but not mac.
I have searched google but no appropriate result
let say I want to create a shortcut to google.com on desktop, then we could run the python function
createShortcut("www.google.com","~/Desktop")
what could be the function body?
You can create a macos .url file inside the function. It is formatted as follows:
[InternetShortcut]
URL=http://www.yourweb.com/
IconIndex=0
Here is a sample implementation:
import os
def createShortcut(url, destination):
# get home directory if ~ in destination
if '~' in destination:
destination = destination.replace('~', os.path.expanduser("~"))
# macos .url file format
text = '[InternetShortcut]\nURL=https://{}\nIconIndex=0'.format(url)
# write .url file to destination
with open(destination + 'my_shortcut.url', 'w') as fw:
fw.write(text)
return
createShortcut("www.google.com", '~/Desktop/')

Python: Creating and writing to a file error

I am having trouble creating and writing to a text file in Python. I am running Python 3.5.1 and have the following code to try and create and write to a file:
from os import *
custom_path = "MyDirectory/"
if not path.exists(custom_path)
mkdir(custom_path)
text_path = custom_path + "MyTextFile.txt"
text_file = open(text_path, "w")
text_file.write("my text")
But I get a TypeError saying an integer is required (got type str) at the line text_file = open(text_path, "w").
I don't know what I'm doing wrong as my code is just about identical to that of several tutorial sites showing how to create and write to files.
Also, does the above code create the text file if it doesn't exist, and if not how do I create it?
Please don't import everything from os module:
from os import path, mkdir
custom_path = "MyDirectory/"
if not path.exists(custom_path):
mkdir(custom_path)
text_path = custom_path + "MyTextFile.txt"
text_file = open(text_path, 'w')
text_file.write("my text")
Because there also a "open" method in os module which will overwrite the native file "open" method.

Python urlretrieve downloading corrupted images

I am downloading a list of images (all .jpg) from the web using this python script:
__author__ = 'alessio'
import urllib.request
fname = "inputs/skyscraper_light.txt"
with open(fname) as f:
content = f.readlines()
for link in content:
try:
link_fname = link.split('/')[-1]
urllib.request.urlretrieve(link, "outputs_new/" + link_fname)
print("saved without errors " + link_fname)
except:
pass
In OSX preview I see the images just fine, but I can't open them with any image editor (for example Photoshop says "Could not complete your request because Photoshop does not recognize this type of file."), and when i try to attach them to a word document, the files are not even showed as picture files in the dialog for browsing for image.
What am i doing wrong?
As J.F. Sebastian suggested me in the comments, the issue was related to the newline in the filename.
To make my script work, you need to replace
link_fname = link.split('/')[-1]
with
link_fname = link.strip().split('/')[-1]

Open text file either locally or remotely via url with python

I am working on a project where I will need to potentially open and read a textfile either on a local server or remotely (via url). Is there a python function that works like php's :
file_get_contents()
that can do this? right now I have:
def get_data_from_file(path):
for i, line in enumerate(open(path)):
.....
I would like to pass in a path either locally or remotely.
You could try:
def file_get_contents(path):
try:
urllib.urlretrieve(path, filename=path)
except:
print 'not a page'
if os.path.exists(path):
with open(path, r) as file:
data = file.read()
print data
else:
print 'no such file'

Categories