invalid path ,Backslashes not allowed [duplicate] - python

This question already has answers here:
Why doesn't calling a string method (such as .replace or .strip) modify (mutate) the string?
(3 answers)
Closed 7 months ago.
I am trying to implement a dropbox app which downloads files from user's Dropbox account.While creating destination path in user's local directory,it crashes saying
Error occured [400] {u'path : u''invalid path /New folder\\img1.jpg : character at index 11 backslashes not allowed}
I thought the dropbox's folder hierarchy uses forward slashes to represent nesting of dorectories, and windows uses backward slashes, so they might be conflicting. Then I used python's BIF replace() as follows for different paths
sample_path.replace( "\\", "/" )
but still
complete_path
variable in my code is giving path containing backslash,after which the program crashes.
the folder hierarchy in my dropbox account is :
New Folder :
Img1.jpg
dtu.jpg
img.jpg
the code is :
def download_file(self,source_path,target_path):
print 'Downloading %s' % source_path
file_path = os.path.expanduser(target_path)
(dir_path,tail) = os.path.split(target_path)
self.check_dir(dir_path)
to_file = open(file_path,"wb")
print source_path+"!!!!!!!!!!!!!!!!!!!!!!!!!!"
source_path.replace("\\","/")
f= self.mClient.get_file(source_path) # request to server !
to_file.write(f.read())
return
def download_folder(self, folderPath):
# try to download 5 times to handle http 5xx errors from dropbox
try:
response = self.mClient.metadata(folderPath)
# also ensure that response includes content
if 'contents' in response:
for f in response['contents']:
name = os.path.basename(f['path'])
complete_path = os.path.join(folderPath, name)
if f['is_dir']:
# do recursion to also download this folder
self.download_folder(complete_path)
else:
# download the file
self.download_file(complete_path, os.path.join(self._target_folder, complete_path))
else:
raise ValueError
except (rest.ErrorResponse, rest.RESTSocketError, ValueError) as error:
print 'An error occured while listing a directory. Will try again in some seconds.'
print "Error occured "+ str(error)

Try this in the Python console to see the issue:
>>> x = "hello"
>>> x.replace("hello", "goodbye")
'goodbye'
>>> x
'hello'
Calling replace on a string doesn't actually modify the string. It returns a new string with the replacement. So you probably want to do this instead:
source_path = source_path.replace("\\", "/")

Related

finding file with unicode characters using Path.glob in python3 on OSX

How do I find a filename starting with "dec2💜file" that has an extension on OSX?
In my case, I have only one .ppt file in the Documents directory. So, the result should be:
dec2💜file.ppt
Here is the code:
my_pathname='Documents'
my_filename='dec2💜file'
my_glob = "{c}.{ext}".format(c=my_filename, ext='*')
try:
my_filename = str(list(pathlib.Path(my_pathname).glob(my_glob))[0])
except Exception as ex:
print("Error - {d}/{f} - {e}".format(d=my_pathname, f=my_glob, e=str(ex)))
exit(1)
print("Found it - {f}".format(f=my_filename))
Current result:
ERROR - Documents/dec2💜file.* - list index out of range
How do I get it to find the file and print:
Found it - dec2💜file.ppt
After creating a folder called test, and a file inside it called dec2💜file.txt, I ran this:
import pathlib
my_pathname = 'test'
my_filename = 'dec2💜file'
my_glob = "{c}.{ext}".format(c=my_filename, ext='*')
try:
my_filename = str(list(pathlib.Path(my_pathname).glob(my_glob))[0])
except Exception as ex:
print("Error - {d}/{f} - {e}".format(d=my_pathname, f=my_glob, e=str(ex)))
exit(1)
print("Found it - {f}".format(f=my_filename))
And got:
Found it - test\dec2💜file.txt
So, I can only conclude there is no folder called Documents inside the working directory where your script runs. Try replacing my_pathname with a full path name, or ensure your script runs in the parent directory of Documents.
You can do this by either changing the working directory of the script from your IDE or on the command line, or by using os.chdir or something similar to change directory before the relevant part of the script.

Is there a way to automate changing the unresolved name in Maya's reference editor?

I'm not sure if this is a kind of beginner question or not, but I've been searching on internet and nothing seemed to solve my problem.
I'm working in a project that requires to change the unresolved name of a referenced object in scene into a form of relative name. Say if I have a sphere in the same folder that my scene's in, and I referenced the sphere into the scene then when I open my reference editor, the 'unresolved name' of the sphere maybe something like path\to\the\sphere. I need to change it to sphere only, for now I'm doing it manually. Is there a way to automate this process by Python?
I used to dealt with editing texture's path before but it's pretty easy since I can use the fileTextureName attribute to change the path and set the path directly. It will be great if reference nodes have some attribute like this
I expect the result of the unresolved name will be from something like path\to\the\ref to ref only
This is a method I made a while back to repath ABC files that travel with our shots to relative paths, so they will resolve even when pushed to an internal asset server.
Your question is a bit vague, but if you look through the method below and ignore whatever checks you don't want, and obviously re-write to deal with .mb or whatever you're using, I think you can make it do what you need.
Please ignore modules in use that you don't need, like consoleLog and config.
def repathAlembicsRelative():
'''Repath all alembics in scene, residing in subfolder MISC, to a relative path'''
out = classes.output()
out.warnings = []
consoleLog('Repathing Alembic caches (sims, etc. Not assets)...')
localFile = cmds.file(query=True, l=True)[0]
localFolder = os.path.dirname(localFile).replace('\\', '/')
for obj in cmds.ls(type='reference'):
try:
filename = cmds.referenceQuery(obj, filename=True, withoutCopyNumber=True)
filename = filename.replace('\\', '/').replace('//', '/')
base = os.path.basename(filename)
dir = os.path.dirname(filename)
# Ref is NOT alembic
if not filename.lower().endswith(config.EXTENSIONS[config.KEY_ALEMBIC]):
consoleLog('Reference {} is NOT an alembic file. Skipping'.format(obj))
continue
# Ref is already on ASSETDIR
if filename.startswith(config.ASSETDIR):
consoleLog('Reference {} resides on ASSETDIR ({}). Skipping'.format(obj, config.ASSETDIR))
continue
# Ref is NOT in subfolder MISC
miscPath = '{}/{}'.format(localFolder, config.KEY_MISC)
miscPathFull = '{}/{}'.format(miscPath, base)
if not filename == miscPathFull:
consoleLog('Reference {} is local, but NOT in the MISC folder. Collecting file before repathing'.format(obj))
try:
if not os.path.isdir(miscPath):
os.makedirs(miscPath)
shutil.copy(filename, miscPathFull)
consoleLog('Copied file {} to {}'.format(filename, miscPathFull))
except Exception as ex:
warning = 'Unable to collect file {}: {}'.format(filename, ex)
consoleLog(warning)
out.warnings.append(warning)
continue
# Failsafe
if not os.path.isfile(miscPathFull):
warning = 'File {} passed all checks, but somehow the file does not exist. This is not good.'.format(miscPathFull)
consoleLog(warning)
out.warnings.append(warning)
continue
# Skip repath if the UNRESOLVED path is already the same as what we're intending to set it to
relPath = '{}/{}'.format(config.KEY_MISC, base)
try:
unresolved = cmds.referenceQuery(obj, filename=True, unresolvedName=True)
if unresolved == relPath:
consoleLog('Unresolved filename for {} ({}) is already correct. Skipping'.format(obj, unresolved))
continue
except Exception as ex:
consoleLog('Unable to read unresolved filename for {}. Proceeding with pathmapping'.format(obj))
# Passed all checks, repath to relative
consoleLog('Repathing {} to {}'.format(filename, relPath))
cmds.file(relPath, loadReference=obj, type='Alembic', options='v=0')
except Exception as e:
consoleLog('Unable to process reference node {}: {}'.format(obj, e))
continue
out.success = True # This method is always successful, but may produce warnings
consoleLog('Done!')
return out
Thank you so much #itypewithmyhands!!! I didnt know that we can use the maya file command to load (or reload) the reference directly from a relative path. So I came up with a simple solution (all the exception I caught earlier on the code above this)
for i in sel:
charRefPath = cmds.referenceQuery(i, filename = 1)
#REPATH UNRESOLVED REFERENCE NAME WITH RELATIVE NAME
refNode = cmds.referenceQuery(i, referenceNode = True)
relPath = charRefPath.split('/')[-1]
cmds.file(relPath, loadReference = refNode)

Flask The system cannot find the path specified: '130.127.5.9'

I've just started experimenting with flask and
I am trying to list a network driver using it. This is the command that I type on my browser. But I get an error that it cant find the path
http://127.0.0.1:5000/130.13.5.8/D/dir/
The function works for local drivers without an issue
I know why it fails. It needs 2 '\' before the actual ip or 4 '\\' .
But when I try http://127.0.0.1:5000/////130.13.5.8/D/dir/
it doesnt work.
I even tried %F%F it also doesn't seem to do the trick.
#app.route('/<path:filepath>/dir/')
def get_dir(filepath):
dir_listing = ''
for entry in os.listdir(filepath):
entry_type = 'dir' if os.path.isdir(os.path.join(filepath, entry)) else 'file'
dir_listing += '{entry_name}|{entry_type}|'.format(entry_name=entry, entry_type=entry_type)
return dir_listing
For anyone having the same issue my workaround is the following
from ipaddress import ip_address
try:
ip_address(filepath.split('/')[0])
filepath = '\\\\{filepath}'.format(filepath=filepath)
except ValueError as e:
pass

Try block catches wrong exception

I'm trying to create a folder, handling the different errors (FileExistsError if the folder already exists and OSError if the folder's name contains illegal characters), but Python seems to always choose the first except block when catching an error no matter which one it is and the order they are.
Is there anything I didn't understand?
import os
from pathlib import Path
def generateSetup(name) :
dir_path = os.path.dirname(os.path.realpath(__file__))
if not Path(dir_path + '/setups').exists() : os.mkdir(dir_path + '/setups')
try : os.mkdir(dir_path + '/setups/' + name)
except FileExistsError : print('The file already exists')
except OSError : print('The name contains illegal characters')
stp_name = input('Enter your setup\'s name :')
generateSetup(stp_name)
There is nothing wrong with your code. It works properly as intended, catches FileExistsError if the directory already exists or OSError if the directory name contains invalid symbols. So I assume the problem is in the way you are testing the code
>>> dloc='tmp/\/b'
>>> try:
... os.mkdir(dloc)
... except FileExistsError:
... print('The file already exists')
... except OSError:
... print('The name contains illegal characters')
...
The name contains illegal characters
we can give any name to directory there is no naming conventions to follow for creating directory through python code.
In this case only the first except block will throw the message if entered name is already a directory name otherwise not.

How can I get around this try except block?

I wrote a try except block that I now realize was a bad idea because it keep throwing 'blind' exceptions that are hard to debug. The problem is that I do not know how to go about writing it another way besides going through each of the methods that are called and manually reading all the exceptions and making a case for each.
How would you structure this code?
def get_wiktionary_audio(self):
'''function for adding audio path to a definition, this is meant to be run before trying to get a specific URL'''
#this path is where the audio will be saved, only added the kwarg for testing with a different path
path="study_audio/%s/words" % (self.word.language.name)
try:
wiktionary_url = "http://%s.wiktionary.org/wiki/FILE:en-us-%s.ogg" % (self.word.language.wiktionary_prefix, self.word.name)
wiktionary_page = urllib2.urlopen(wiktionary_url)
wiktionary_page = fromstring(wiktionary_page.read())
file_URL = wiktionary_page.xpath("//*[contains(concat(' ', #class, ' '), ' fullMedia ')]/a/#href")[0]
file_number = len(self.search_existing_audio())
relative_path = '%s/%s%s.ogg' % (path, self.word.name, file_number)
full_path = '%s/%s' % (settings.MEDIA_ROOT, relative_path)
os.popen("wget -q -O %s 'http:%s'" % (full_path, file_URL))
except:
return False
WordAudio.objects.create(word=self.word, audio=relative_path, source=wiktionary_url)
return True
Often, exceptions come with error strings which can be used to pinpoint the problem. You can access this value like so:
try:
# code block
except Exception as e:
print str(e)
You can also print what class of exception it is along with any error messages by using the repr method:
try:
# code block
except Exception as e:
print repr(e)
One way I like to go about it is configure Python logging and log the output. This gives you a lot of flexibility in what you do with the log output. The below example logs the exception traceback.
import traceback
import logging
logger = logging.getLogger(__name__)
try:
...
except Exception as e:
logger.exception(traceback.format_exc()) # the traceback
logger.exception(e) # just the exception message
First your code is un-pythonic. You are using 'self' for a function. "self" is usually reserved for a class. So in reading your code, it feels unnatural. Second, my style is to line up "=" signs for readability. My advice is to start over -- Use standard pythonic conventions. You can get this by going through python tutorials.
Throw exception early and often -ONLY when the code stops running. You could also move some of the naming outside the try/except block.
def get_wiktionary_audio(self):
'''function for adding audio path to a definition, this is meant to be run before trying to get a specific URL'''
#this path is where the audio will be saved, only added the kwarg for testing with a different path
path = "study_audio/%s/words" % (self.word.language.name)
try:
wiktionary_url = "http://%s.wiktionary.org/wiki/FILE:en-us-%s.ogg" % (self.word.language.wiktionary_prefix, self.word.name)
wiktionary_page = urllib2.urlopen(wiktionary_url)
wiktionary_page = fromstring(wiktionary_page.read())
file_URL = wiktionary_page.xpath("//*[contains(concat(' ', #class, ' '), ' fullMedia ')]/a/#href")[0]
file_number = len(self.search_existing_audio())
relative_path = '%s/%s%s.ogg' % (path, self.word.name, file_number)
full_path = '%s/%s' % (settings.MEDIA_ROOT, relative_path)
os.popen("wget -q -O %s 'http:%s'" % (full_path, file_URL))
except Exception as e : print e
WordAudio.objects.create(word=self.word, audio=relative_path, source=wiktionary_url)
return True

Categories

Resources