我有一个运行 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.Popen和 https://docs.python.org/2/library/subprocess.html#subprocess.Popen :
You do not need
shell=True
to run a batch file or console-based executable.
那么,让我们试试:
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/