【问题标题】:Python subprocess on win32 not working without with shell=Truewin32 上的 Python 子进程在没有 shell=True 的情况下无法工作
【发布时间】:2015-03-10 01:09:56
【问题描述】:

这可能看起来很奇怪,但我正在尝试通过 subprocess.check_call() 在 Python 脚本中使用 Perl 的 CPAN。由于某种原因它不起作用并给出以下错误:

WindowsError: [Error 2] The system cannot find the file specified

当我尝试正常运行命令时。

使用 shell=True 可以解决问题,但我读到这可能会带来一些安全问题。有人可以向我解释为什么会这样吗?有办法解决吗?

编辑:示例代码

这是我使用 check_call() 遍历列表的方式:

packages = {'DateTime':'2','Win32::API':'2','Date::Manip':'2','XML::LibXML':'2','Carp::Assert':'2',
                    'Digest::CRC':'2','Data::Hexify':'2','Image::ExifTool':'2','File::Mork':'2','DateTime::Format::Strptime':'2',
                    'Parse::Win32Registry':'2','HTML::Scrubber':'2','Mac::PropertyList':'2','XML::Entities':'2'}

for k,v in packages.iteritems():
    try:
        res = check_call(shlex.split('cpan install %s' % k), shell=True)
        if res == 0:
            v = 0
    except CalledProcessError:

谢谢!

【问题讨论】:

  • 您要运行什么命令?它在哪里生活?您是使用完整路径还是仅使用裸名?
  • 我正在尝试运行许多命令来安装 perl 包,例如一个是 'cpan install Win32::API'... 都遵循相同的约定,其中 Win32::API 是包名称...这只是裸名,但 cpan 目录在我的系统和用户 %PATH%
  • 你能举一个例子来说明你是如何编写你的 check_call() 的吗?
  • 编辑了一个例子,感谢您的帮助!
  • 使用cpan 的完整路径是否可以在不使用 shell 的情况下工作?

标签: python shell subprocess


【解决方案1】:

subprocess.Popen(),重定向标准输出,以便您检查输出。

import subprocess as s
import shlex

k = "DateTime"

proc = s.Popen(["cpan", "install", k], stdout=s.PIPE)
output, err = proc.communicate()

print output, err

【讨论】:

  • 我和check_call()有同样的错误
  • 请输入输出:import osprint os.environ["COMSPEC"]
  • C:\\Windows\\system32\\cmd.exe
  • 这真的很奇怪。根据the popen constructor part of the python docs,它说在 Windows 上你应该使用 shell=True 的唯一时间是你调用内置函数的时候。我很确定 cpan 不是 Windows 内置的。
  • 对,cpan肯定不是,我今天在Strawberry perl下安装的,完整路径是c:\strawberry\perl\bin\cpan
猜你喜欢
  • 2018-03-22
  • 1970-01-01
  • 2016-04-16
  • 1970-01-01
  • 1970-01-01
  • 2012-04-01
  • 1970-01-01
  • 2012-06-05
  • 2012-12-21
相关资源
最近更新 更多