【问题标题】:Call subprocess.Popen() when the working directory is on a UNC path, not a mapped drive当工作目录位于 UNC 路径而不是映射驱动器时调用 subprocess.Popen()
【发布时间】:2011-07-08 09:55:24
【问题描述】:

我想运行一个可执行文件,它对位于远程文件管理器上的数据集执行一些处理。作为设计的一部分,我希望文件管理器的位置灵活,并且在运行时传递给我的 python 程序。

我整理了以下代码来说明我的问题,但使用python 命令,所以任何人都可以运行它:

#!/usr/bin/env python
import os
import subprocess

def runMySubProcess(cmdstr, iwd):
    p = subprocess.Popen(cmdstr,
        shell=True,
        cwd=iwd,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    (stdout, stderr) = p.communicate()
    if stderr:
        raise IOError, stderr
    return stdout

if __name__ == '__main__':
    print runMySubProcess('python -h', 'C:\\')
    print runMySubProcess('python -h', '\\\\htpc\\nas')

只要iwd 位于已映射到计算机上的驱动器号的共享上,此功能就非常有效。但如果iwd 是UNC 路径,则subprocess.Popen() 调用以stderr 输出结束,进而引发IOError 异常:

Traceback (most recent call last):
  File "test.py", line 19, in <module>
    print runMySubProcess('dir', '\\\\htpc\\nas')
  File "test.py", line 14, in runMySubProcess
    raise IOError, stderr
IOError: '\\htpc\nas'
CMD.EXE was started with the above path as the current directory.
UNC paths are not supported.  Defaulting to Windows directory.

有没有办法让这个子进程调用工作而不是求助于解析iwd 并在子进程命令执行时存在的机器上进行临时驱动器挂载?我想避免必须管理驱动器安装的创建和清理。当然,我宁愿不必处理(尽管不太可能)机器上当前正在使用所有驱动器号的情况。

【问题讨论】:

    标签: python windows subprocess unc


    【解决方案1】:

    问题不在于Popen,,而在于cmd.exe,它不允许工作目录成为UNC 路径。它只是没有;试试吧。假设您正在运行的任何可执行文件都可以处理 UNC 路径,那么您可能会在您的 Popen() 调用中指定 shell=False 运气更好,但当然,如果您尝试运行的是内置于 @987654325 的命令@你别无选择。

    【讨论】:

    • 明确认识到问题出在cmd.exe——我会试试shell=False。谢天谢地,我试图运行的不是 cmd.exe 内置的。
    • 我更新了问题以使用python -h 作为命令而不是dir。将shell=True 更改为shell=False 已经为我解决了这个问题。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-13
    • 1970-01-01
    • 2023-03-27
    • 2016-04-21
    • 1970-01-01
    相关资源
    最近更新 更多