来自两者https://docs.python.org/3/library/subprocess.html#subprocess.Popen https://docs.python.org/3/library/subprocess.html#subprocess.Popen and https://docs.python.org/2/library/subprocess.html#subprocess.Popen https://docs.python.org/2/library/subprocess.html#subprocess.Popen:
你不需要shell=True
运行批处理文件或基于控制台的可执行文件。
已经一样由 @JBernardo 引用 https://stackoverflow.com/questions/16137556/windows-subprocess-popen-a-batch-file-without-shell-true#comment23054228_16137556.
那么,让我们尝试一下:
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]
所以这does如果指定完整路径,则有效。我认为当你有一个错字时这次经历 https://stackoverflow.com/questions/16137556/windows-subprocess-popen-a-batch-file-without-shell-true#comment23054022_16137556。可能是你写的.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')])