如何运行已安装的Python脚本?
我用distutils来安装我的Python包,使用了这个setup.py:
import distutils.core
args = {
'name' : 'plugh',
'version' : '1.0',
'scripts' : [ "scripts/plugh" ],
'packages': [ "plugh" ],
}
d = distutils.core.setup(
**args
)
在Linux或Mac上,它按预期工作:
% plugh
hello world
%
但在Windows上,脚本"plugh"却无法运行:
C:\Python25\Scripts>plugh
'plugh' is not recognized as an internal or external command,
operable program or batch file.
C:\Python25\Scripts>
我发现了一个错误报告,地址是 http://bugs.python.org/issue7231,里面提到安装Python时,\Scripts目录没有被添加到PATH环境变量中,所以我按照那个报告里的解决方法,把C:\Python25\Scripts添加到了PATH里。
C:\Python25\Scripts>path
PATH=c:\Python25\Scripts;C:\Program Files\Legato\nsr\bin;C:\WINDOWS\system32;C:\
WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files\QuickTime\QTSystem\;c:\python2
5;c:\local;C:\WINDOWS\system32\WindowsPowerShell\v1.0
这是不是在Windows上就不行的事情?如果真是这样,那在Windows机器上应该怎么使用Python脚本呢?
我想我可以检测到系统是Windows,然后在列表中添加一个额外的脚本,叫做"plugh.bat",里面包含类似这样的内容:
@echo off
c:\python25\python.exec c:\python25\scripts\plugh %1 %2 %3 %4 %5 %6 %7 %8 %9
但这样做真的是正确的解决办法吗?我本以为distutils在Windows上有这么多定制功能,应该会有更好的解决方案。
2 个回答
如果你使用 ActivePython,在安装的时候,它会自动把
C:\PythonXY\Scripts
这个文件夹加到你的%PATH%
里(ActivePython 2.6 还会把 PEP 370 的%APPDATA%\Python\Scripts
也加到%PATH%
里)。在 Windows 机器上部署脚本时,最好使用 Distribute,它会帮你处理脚本的 .exe 包装,并且会调用你安装包时用的实际 Python(这样可以避免多个 Python 安装之间的冲突——所以仅仅把脚本命名为 .py 是不够的)。想了解更多,可以看看 Distribute 文档中的 入口点。
Windows通过文件的后缀名来判断这个文件应该怎么运行。
把你的文件命名为 plugh.py
,然后在命令行里输入 plugh.py
来运行它。