I am trying to use QDesktopServices to have system open the files or folders specified.
The code below works perfect for paths which doesn't have spaces in them but fails to execute if otherwise
def openFile(self):
print self.oVidPath
print "\n"
url = QUrl(self.oVidPath)
QDesktopServices.openUrl(url)
self.Dialog.close()
and the output for paths with spaces is
/home/kerneldev/Documents/Why alcohol doesn't come with nutrition facts.mp4
gvfs-open: /home/kerneldev/Documents/Why%20alcohol%20doesn't%20come%20with%20nutrition%20facts.mp4: error opening location: Error when getting information for file '/home/kerneldev/Documents/Why%20alcohol%20doesn't%20come%20with%20nutrition%20facts.mp4': No such file or directory
I have verified that the path specified exists.
Please Help
You need to use a file:// url, otherwise QUrl will treat the path as a network url and will encode it for use in that context. So try this instead:
url = QUrl.fromLocalFile(self.oVidPath)
Related
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/')
I tried using wget:
url = https://yts.lt/torrent/download/A4A68F25347C709B55ED2DF946507C413D636DCA
wget.download(url, 'c:/path/')
The result was that I got a file with the name A4A68F25347C709B55ED2DF946507C413D636DCA and without any extension.
Whereas when I put the link in the navigator bar and click enter, a torrent file gets downloaded.
EDIT:
Answer must be generic not case dependent.
It must be a way to download .torrent files with their original name.
You can get the filename inside the content-disposition header, i.e.:
import re, requests, traceback
try:
url = "https://yts.lt/torrent/download/A4A68F25347C709B55ED2DF946507C413D636DCA"
r = requests.get(url)
d = r.headers['content-disposition']
fname = re.findall('filename="(.+)"', d)
if fname:
with open(fname[0], 'wb') as f:
f.write(r.content)
except:
print(traceback.format_exc())
Py3 Demo
The code above is for python3. I don't have python2 installed and I normally don't post code without testing it.
Have a look at https://stackoverflow.com/a/11783325/797495, the method is the same.
I found an a way that gets the torrent files downloaded with their original name like as they were actually downloaded by putting the link in the browser's nav bar.
The solution consists of opening the user's browser from Python :
import webbrowser
url = "https://yts.lt/torrent/download/A4A68F25347C709B55ED2DF946507C413D636DCA"
webbrowser.open(url, new=0, autoraise=True)
Read more:
Call to operating system to open url?
However the downside is :
I don't get the option to choose the folder where I want to save the
file (unless I changed it in the browser but still, in case I want to save
torrents that matches some criteria in an other
path, it won't be possible).
And of course, your browser goes insane opening all those links XD
I have verified that Py is running as the same user. I am running locally and writing to a share, but the home dir (where Py is running from) shouldn't matter. Same error whether destination file (pull.zip) exists or not. Shouldn't have to run elevated for this. Same result in Py 2 or 3.
import requests, io
url = "https://someplace/stuff.zip"
loc = "\\domain\share\pull.zip"
r = requests.get(url)
print (r.status_code)
with open(loc, 'w+b') as code:
code.write(r.content)
Returns this:
PermissionError: [Errno 13] Permission denied:
'\\domain\\share\\pull.zip'
(paths have been anonymized)
Efective Permissions on destination folder.
\\ is an escape sequence interpreted as a single backslash.
You can use four backslashes to represent two of them (but this will fail if the literal contains another escape sequence)
loc = "\\\\domain\share\pull.zip"
or a raw literal
loc = r"\\domain\share\pull.zip"
If your "pull.zip" is local ("pull.zip" is in folder "share" which is in folder "domain" which is in the current directory of your python file) than you should remove \\ from start of string loc and double all other slashes. So your code should look like this:
import requests, io
url = "https://someplace/stuff.zip"
loc = "domain\\share\\pull.zip"
r = requests.get(url)
print (r.status_code)
with open(loc, 'w+b') as code:
code.write(r.content)
Flask-uploads has something called UploadSet which is described as a "single collection of files". I can use this upload set to save my file to a predefined location. I've defined my setup:
app = Flask(__name__)
app.config['UPLOADS_DEFAULT_DEST'] = os.path.realpath('.') + '/uploads'
app.config['UPLOADED_PHOTOS_ALLOW'] = set(['png', 'jpg', 'jpeg'])
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
# setup flask-uploads
photos = UploadSet('photos')
configure_uploads(app, photos)
#app.route('/doit', method=["POST"])
def doit():
myfile = request.files['file']
photos.save(myfile, 'subfolder_test', 'filename_test')
return ''' blah '''
This should save to ./uploads/photos/subfolder_test/filename_test.png
My test image is: 2.6MB and is a png file. When I upload this file, I get the error:
...
File "/home/btw/flask/app.py", line 57, in doit
photos.save(myfile, 'subfolder_test', 'filename_test')
File "/usr/local/lib/python2.7/dist-packages/flaskext/uploads.py", line 388, in save
raise UploadNotAllowed()
UploadNotAllowed
However it doesn't say exactly what is not allowed. I have also tried removing all constraints, but the app still throws this error. Why?
EDIT:
Okay, so I figured out that it's not actually the constraints that is causing the problem. It is the subfolder and/or the filename that is causing the problem:
# This works
# saves to: ./uploads/photos/filename_test.png
photos.save(myfile)
But I want to save to my custom location ./uploads/photos/<custom_subdir>/<custom_filename>. What is the correct way of doing this?
You need to give your filename_test the extension as well
photos.save(myfile, 'subfolder_test', 'filename_test.png')
The UploadSet checks the extension on the new file name and will throw the exception if the new extension is not allowed.
Since you are not giving the new file an extension, it does not recognize it.
You can add a dot to file's name, then the file's extension will be appended.
photos.save(myfile, 'subfolder_test', 'filename_test' + '.')
save(storage, folder=None, name=None)
Parameters:
storage – The uploaded file to save.
folder – The subfolder within the upload set to save to.
name – The name to save the file as. If it ends with a dot, the file’s extension will be appended to the end.
I need to get the content of the resources received in command line. The user can write a relative path to a file or an URL. Is it possible to read from this resource regardless if it is a path to a file or an URL?
In Ruby I have something like the next, but I'm having problems finding a Python alternative:
content = open(path_or_url) { |io| io.read }
I don't know of a nice way to do it, however, urllib.request.urlopen() will support opening normal URLs (http, https, ftp, etc) as well as files on the file system. So you could assume a file if the URL is missing a scheme component:
from urllib.parse import urlparse
from urllib.request import urlopen
resource = input('Enter a URL or relative file path: ')
if urlparse(resource).scheme == '':
# assume that it is a file, use "file:" scheme
resource = 'file:{}'.format(resource)
data = urlopen(resource).read()
This works for the following user input:
http://www.blah.com
file:///tmp/x/blah
file:/tmp/x/blah
file:x/blah # assuming cwd is /tmp
/tmp/x/blah
x/blah # assuming cwd is /tmp
Note that file: (without slashes) might not be a valid URI, however, this is the only way to open a file specified by relative path, and urlopen() works with such URIs.