python - Windows subprocess.Popen 没有 shell=True 的批处理文件

标签 python windows shell subprocess

我有一个运行 lessc 的函数(使用 npm install -g less 安装):

>>> import subprocess
>>> subprocess.Popen(['lessc'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\subprocess.py", line 679, in __init__
    errread, errwrite)
  File "C:\Python27\lib\subprocess.py", line 896, in _execute_child
    startupinfo)
WindowsError: [Error 2] The system cannot find the file specified

不幸的是,除非我添加 shell=True,否则它不起作用:

>>> subprocess.Popen(['lessc'], shell=True)
<subprocess.Popen object at 0x01F619D0>

如何在不使用 shell=True 的情况下让 lessc 运行?

最佳答案

来自https://docs.python.org/3/library/subprocess.html#subprocess.Popenhttps://docs.python.org/2/library/subprocess.html#subprocess.Popen :

You do not need shell=True to run a batch file or console-based executable.

已经cited by @JBernardo .

那么,让我们试试:

lessc 实际告诉的地方

C:\Users\myname\AppData\Roaming\npm\lessc
C:\Users\myname\AppData\Roaming\npm\lessc.cmd

也就是说,要执行的文件是 lessc.cmd,而不是某个 .bat 文件。事实上:

>>> import subprocess
>>> subprocess.Popen([r'C:\Users\myname\AppData\Roaming\npm\lessc.cmd'])
<subprocess.Popen object at 0x035BA070>
>>> lessc: no input files

usage: lessc [option option=parameter ...] <source> [destination]

因此,如果您指定完整路径,这确实有效。我假设当你有一个错字 this experience .可能是您编写了 .bat 而不是 .cmd


如果您不想将 lessc 的完整路径修补到您的脚本中,您可以为自己烘焙一个where:

import plaform
import os

def where(file_name):
    # inspired by http://nedbatchelder.com/code/utilities/wh.py
    # see also: http://stackoverflow.com/questions/11210104/
    path_sep = ":" if platform.system() == "Linux" else ";"
    path_ext = [''] if platform.system() == "Linux" or '.' in file_name else os.environ["PATHEXT"].split(path_sep)
    for d in os.environ["PATH"].split(path_sep):
        for e in path_ext:
            file_path = os.path.join(d, file_name + e)
            if os.path.exists(file_path):
                return file_path
    raise Exception(file_name + " not found")

然后你可以这样写:

import subprocess
subprocess.Popen([where('lessc')])

关于python - Windows subprocess.Popen 没有 shell=True 的批处理文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16137556/

相关文章:

python - 用 Python 绘制频率扫描图

windows - 无法通过 SSH 连接到 Azure Windows Server VM

python - 从命令行禁用对 python 程序的文件访问

python - 在 SQLAlchemy 中使用 cdecimal

python - numpy数组转入matlab

python - Pyephem 本地时间问题

c++ - 程序是否针对不同的操作系统分别编码?

windows - 为什么较新的 Windows 版本仍支持某些旧的 Win16 API?

linux - 查看目录中文件的脚本

linux - SHELL:定义字符串时如何使用或运算符