0

I have this piece of python/tkinter code that is trying to rename a directory. When the call() gets executed it trows an error.

if os.path.exists(self.destDirectory):
    self.now = datetime.datetime.now()
    print(self.now)
    self.now = str(self.now.strftime("%Y_%m_%d_%H_%M"))
    print('rename {0} {1}'.format(self.destDirectory, 'old_' + self.now))
    self.cmd1 = ('rename {0} {1}'.format(self.destDirectory, 'old_' + self.now))
    self.returnCode1 = call(self.cmd1)

ERROR:

Exception in Tkinter callback Traceback (most recent call last):  
File "C:\Python32\lib\tkinter\__init__.py", line 1399, in __call__
    return self.func(*args)
File "C:\EclipseWorkspaces\csse120\Myproject\src\BoxRestore.py", line 95, in proceed
    self.returnCode1 = call(self.cmd1)
File "C:\Python32\lib\subprocess.py", line 467, in call
    return Popen(*popenargs, **kwargs).wait()
File "C:\Python32\lib\subprocess.py", line 741, in __init__
    restore_signals, start_new_session)
File "C:\Python32\lib\subprocess.py", line 960, in _execute_child
    startupinfo)
WindowsError: [Error 2] The system cannot find the file specified

But When I do:

print('rename {0} {1}'.format(self.destDirectory, 'old_' + self.now))

And execute it in cmd I get no errors.

Another command Won't complain:

self.cmd2 = ('xcopy {0} {1} /I /E'.format(self.values['sourceButton'], self.values['destinationButton']))
self.returnCode = call(self.cmd2)

Can You Please Help.

4

2 に答える 2

2

You should use this:

if os.path.exists(self.destDirectory):
    self.now = datetime.datetime.now()
    print(self.now)
    self.now = str(self.now.strftime("%Y_%m_%d_%H_%M"))
    print('rename {0} {1}'.format(self.destDirectory, 'old_' + self.now))
    os.rename( self.destDirectory, 'old_' + self.now )
于 2013-03-25T00:48:47.803 に答える
2

There's no "rename" program on Windows.

Instead, "rename" is a built-in command in the command prompt program (cmd.exe). So when you type "rename" at a command prompt, it gets treated specially by cmd.exe.

When you run a program using Python's subprocess module, then (by default) it doesn't use cmd.exe, it tries to run an actual program. This doesn't work for rename. You can change this by passing the shell=True option to subprocess.call; if you do that then it should work. (This also introduces a security vulnerability if you're getting any part of the command line from the Internet or something else you can't trust, which is why it's not the default).

But using os.rename() is a MUCH better solution - you get better error handling, your program will be faster, more reliable, more secure, simpler, easier for other programmers to understand, and portable to Linux/Mac. (One example of "more reliable": your current code breaks if the directory name contains a space; but os.rename() will just work).

于 2013-03-25T01:33:44.387 に答える