窗户子流程.Popen没有shell=Tru的批处理文件

2024-05-19 23:03:23 发布

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

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

^{pr2}$

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


Tags: install函数inpyimporttruenpmlib
2条回答

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。在

所以,让我们试试:

where lessc实际上说明

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

这意味着,要执行的文件是lessc.cmd,而不是某个.bat文件。事实上:

^{pr2}$

因此,如果指定完整路径,则该确实有效。我想你在写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')])

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

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

相关问题 更多 >