繁体   English   中英

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

[英]Windows subprocess.Popen a batch file without shell=True

我有一个运行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运行lessc

将文件更改为lessc.bat,或创建调用lessc的.bat文件。 这样,Windows将文件识别为批处理文件并将正确执行。

根据.bat文件的位置,您可能还需要设置cwd。

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

您不需要shell=True来运行批处理文件或基于控制台的可执行文件。

正如@JBernardo所引用的那样

所以,让我们尝试:

where 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]

因此,如果指定完整路径,这确实有效。 我假设你有这种经历时会涉及一个错字。 可能是你写的.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')])

暂无
暂无

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

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