尝试通过python中的cmd命令重命名目录时出错

时间:2013-03-24 23:18:10

标签: python cmd tkinter

我有一段试图重命名目录的python / tkinter代码。当call()被执行时,它会出错。

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

但是当我这样做时:

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

在cmd中执行它我没有错误。

另一个命令不会抱怨:

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

你能帮忙吗?

2 个答案:

答案 0 :(得分:2)

你应该用这个:

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 )

答案 1 :(得分:2)

Windows上没有“重命名”程序。

相反,“rename”是命令提示程序(cmd.exe)中的内置命令。因此,当您在命令提示符下键入“rename”时,它会被cmd.exe专门处理。

当您使用Python的subprocess模块运行程序时,(默认情况下)它不使用cmd.exe,它会尝试运行实际的程序。这不适用于rename。您可以将shell=True选项传递给subprocess.call来更改此设置。如果你这样做那么它应该工作。 (如果您从Internet获取命令行的任何部分或其他您不能信任的内容,这也会引入安全漏洞,这就是默认情况下的原因。)

但使用os.rename()是一个 MUCH 更好的解决方案 - 您可以获得更好的错误处理,您的程序将更快,更可靠,更安全,更简单,更容易让其他程序员理解,并可移植到Linux / Mac。 (“更可靠”的一个例子:如果目录名称包含空格,则当前代码会中断;但os.rename()将起作用。)