和字号需要逃走吗?

2024-06-10 03:47:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在python2.7.8中创建一个函数来删除远程PC上不再需要的文件

如果我从命令行运行它,我可以执行以下操作:

C:\>del /f /q \\RemotePC\d$\temp\testfile.txt && if exist \\RemotePC\d$\temp\testfile.txt (set errorlevel=1) else (set errorlevel=0)

由此我得到了预期的结果:

^{pr2}$

但是,当我试图把它放到python函数中时,它不起作用。未设置测试变量。在

下面是我的python函数:

def DelFile(self, address, del_file):
    cmd_line = "del /f /q \\\\" + address + del_file + "\&\& if exist \"\\\\" + address + del_file + "\" (set errorlevel=1) else (set errorlevel=0)"

    myP = subprocess.Popen(cmd_line, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)

    out = timeout(myP.communicate, (), {}, 120, (None, None))
    result = out[0]
    error = out[1]
    error_code = None
    error_code = myP.returncode
    notes = []

    return cmd_line, result, error, error_code, notes

我已经验证了addressdel_file变量的格式是否正确,以便找到所需的文件。我还验证了它是否会根据情况删除或不删除预期的文件。但由于某些原因,测试变量从未设置。在

我的理解是和字元需要转义,就像在字符串中使用时"\&"。这不是真的,还是我没有正确地逃避?在


Tags: 文件函数cmdnoneaddresslinecodeerror
2条回答

你的命令行应该是这样的

cmd_line = "del /f /q \\\\{0}{1} & if exist \\\\{0}{1} (set test=1) else (set test=0)".format(address, del_file)

尝试使用一个&

我发现了问题,结果发现我确实有一些。第一个是和号显然不需要被转义(谢谢FirebladeDan),第二个是我在和号之前缺少了一个空格(再次感谢FirebladeDan提供了格式化技巧,这就是我如何注意到缺少空格的原因)。最后一个与python相比更像CMD的问题,我试图直接设置errorlevel变量,而我本应该使用1或{}的{}。在

作为补充说明,我还添加了在使用psexec时,它不是解决方案所必需的,它只是有助于提高整个程序的性能。在

我最后得出的结论是:

def DelFile(self, address, del_file):
    cmd_line = r'psexec \\{0} cmd /c "del /f /q "{1}" && if exist "{1}" (exit /b 1) else (exit /b 0)"'.format(address, del_file)

    myP = subprocess.Popen(cmd_line, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)

    out = timeout(myP.communicate, (), {}, 60, (None, None))
    result = out[0]
    error = out[1]
    error_code = None
    error_code = myP.returncode
    notes = []

    return cmd_line, result, error, error_code, notes

相关问题 更多 >