So I am fairly new with coding in Python and in general and I am trying to write a program that will backup files in a giving folder. However, I continue to get a "NameError: name 'src' is not defined. I see some other questions similar about this error but none have yet to make me understand what I am doing wrong or why I get this error. As far as I understand it I am defining 'src' in the code below. Any help would be greatly appreciated.
ERROR:
File "/home/student/PycharmProjects/Lab1.py/Lab5.5.py", line 1, in processing
backup(src, dest)
NameError: name 'src' is not defined
def backup(src, dest):
#Checking if src and dest directories exist
sourceFilePath = input('Enter folder path to be backed up')
destFilePath = input('Please choose where you want to place the backup')
#found = true
for directory in [src, dest]:
if not isdir(directory):
print(f'could not find {directory}')
found = False
if not found:
exit(1)
#for each file in src
for sourceFileName in listdir(src):
#computing file paths
sourceFilePath = path.join(src, sourceFileName)
destFilePath = path.join(dest, sourceFileName)
#backing up file
copy2(sourceFilePath, destFilePath)
#entry point
if __name__=='__main__':
#validating length of command line arguments
if len(argv) != 3:
print(f'Usage: {argv[0]} SRC DEST')
exit(1)
#performing backup
backup(argv[1], argv[2])
#logging status message
print('Backup succesful!')
why are you prompting the user for src and dest path though you already pass them as command args? The issue probably came from the fact you didn't provide the src arg while running the script. Things like
python script.py srcpath dstpath
Related
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.
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)
I'm getting an error
('The system can not find the specified path', 'A \ *. *').
How to solve this error? I'm not getting what went wrong.
def validatepath(status, userpath):
if status:
folders = [fol for fol in os.listdir(userpath) if os.path.isdir(os.path.join(userpath,fol))]
businesslogic(folders, userpath)
else:
print('Invalid Path')
if __name__ == '__main__':
userPath = input('Enter Directory Path: ')
status = checkpath(userPath)
directories = validatepath(status, userPath)
folders = [fol for fol in os.listdir(userpath) if os.path.isdir(os.path.join(userpath,fol))]
Your current code only shows the list of sub-dir of userpath. That is the reason why you got an error when you try to call that directory.
Try this:
folder = [os.path.join(userpath,fol) for fol in os.listdir(userpath) if os.path.isdir(os.path.join(userpath,fol))]
I'm creating a really basic program that simulates a terminal with Python3.6, its name is Prosser(The origin is that "Prosser" sounds like "Processer" and Prosser is a command processer).
A problem that I'm having is with command import, this is, all the commands are stored in a folder called "lib" in the root folder of Prosser and inside it can have folders and files, if a folder is in the "lib" dir it can't be named as folder anymore, its name now is package(But this doesn't care for now).
The interface of the program is just a input writed:
Prosser:/home/pedro/documents/projects/prosser/-!
and the user can type a command before the text, like a normal terminal:
Prosser:/home/pedro/documents/projects/prosser/-! console.write Hello World
let's say that inside the "lib" folder exists one folder called "console" and inside it has a file called "write.py" that has the code:
class exec:
def main(args):
print(args)
As you can see the first 2 lines is like a important structure for command execution: The class "exec" is the main class for the command execution and the def "main" is the main and first function that the terminal will read and execute also pass the arguments that the user defined, after that the command will be responsible to catch any error and do what it will be created to do.
At this moment, everything is ok, but now comes the true help that I need of U guys, the command import.
Like I writed the user can type any command, and in the example above I typed a "console.write Hello World" and exists one folder called "console" and one file "write.py". The point is that the packages can be defined by a "dot", this is:
-! write Hello World
Above I only typed "write" and this says that the file is only inside the "lib" folder, it doesn't has a package to storage and separate it, so it is a Freedom command(A command that doesn't has packages or nodes).
-! console.write Hello World
Now I typed above "console.write" and this says that the file has a package or node to storage and separate it, this means that it is a Tied command(A command that has packages or nodes).
With that, a file is separated from the package(s) with a dot, the more dots you put, more folders will be navigated to find the file and proceed to the next execution.
Code
Finnaly the code. With the import statement I tryied this:
import os
import form
curDir = os.path.dirname(os.path.abspath(__file__)) # Returns the current direrctory open
while __name__ == "__main__":
c = input('Prosser:%s-! ' % (os.getcwd())).split() # Think the user typed "task.kill"
path = c[0].split('.') # Returns a list like: ["task", "kill"]
try:
args = c[1:] # Try get the command arguments
format = form.formater(args) # Just a text formatation like create a new line with "$n"
except:
args = None # If no arguments the args will just turn the None var type
pass
if os.path.exists(curDir + "/lib/" + "/".join(path) + ".py"): # If curDir+/lib/task/kill.py exists
module = __import__("lib." + '.'.join(path)) # Returns "lib.task.kill"
module.exec.main(args) # Execute the "exec" class and the def "**main**"
else:
pathlast = path[-1] # Get the last item, in this case "kill"
path.remove(path[-1]) # Remove the last item, "kill"
print('Error: Unknow command: ' + '.'.join(path) + '. >>' + pathlast + '<<') # Returns an error message like: "Error: Unknow command: task. >>kill<<"
# Reset the input interface
The problem is that when the line "module = __import__("lib." + '.'.join(path))" is executed the console prints the error:
Traceback (most recent call last):
File "/home/pedro/documents/projects/prosser/main.py", line 18, in <module>
module.exec.main(path) # Execute the "exec" class and the def "**main**"
AttributeError: module 'lib' has no attribute 'exec'
I also tried to use:
module = \_\_import\_\_(curDir + "lib." + '.'.join(path))
But it gets the same error. I think it's lighter for now. I'd like if someone help me or find some replacement of the code. :)
I think you have error here:
You have diffirent path here:
if os.path.exists(curDir + "/lib/" + "/".join(path) + ".py")
And another here, you dont have curDir:
module = __import__("lib." + '.'.join(path)) # Returns "lib.task.kill"
You should use os.path.join to build paths like this:
module = __import__(os.path.join(curdir, 'lib', path + '.py'))
Solved: Adding an os.chdir(myArg) resolved the issue.
I'm getting an error when trying to run the following code on anything other than my home directory or files/direcs that I own.
FileNotFoundError: [Errno 2] No such file or directory:
I created a file in root and changed ownership on the file to pi:pi (user running the script). If I specify that file directly, it works, however if I run the script on "/", it will not read that or any other file/direc. I also created a directory /tempdir_delete/ and changed ownership to pi:pi.. If I run the script specifically on "/tempdir_delete/*", it works, but if I leave off the * it fails.
Why does it fail on all except /home/pi/ or files that I explicitly specify and own? It's running the stat as user pi, which is granted by sudo to perform the stat. Also, why do I have to specify the file that I own explicitly? Shouldn't it see that file in root and work because I own it?
import os
import re
import sys
import pwd
myReg = re.compile(r'^\.')
myUID = os.getuid()
myArg = sys.argv[1]
print(os.getuid())
print(pwd.getpwuid(int(myUID)))
print(myArg)
def getsize(direct):
if os.path.isfile(direct) == True:
statinfo = os.stat(myArg)
print(str(statinfo.st_size))
else:
for i in os.listdir(direct):
try:
statinfo = os.stat(i)
if myReg.search(i):
continue
else:
print(i + ' Size: ' + str(statinfo.st_size))
except:
print('Exception occurred, can't read.')
continue
getsize(myArg)
Solved. Adding an os.chdir(myArg) worked to resolve the issue.