繁体   English   中英

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

[英]Error while trying to rename a directory through cmd command from python

我有这段试图重命名目录的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)

错误:

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)

您能帮忙吗?

您应该使用此:

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 )

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

而是,“重命名”是命令提示符程序( cmd.exe )中的内置命令。 因此,当您在命令提示符下键入“重命名”时, cmd.exe将对其进行特殊处理。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM