Win32下,直接执行系统PATH中 的Python脚本

realfun <[email protected]> Tue, 22 Jan 2008 09:19:05 +0800
Newsgroups gmane.comp.python.chinese
Message-ID <[email protected]>
呵呵,毛遂自荐一个小工具。

Python经常会把脚本装在%Python%\Scripts下面,很难用,执行的时候需要跑到这个目录下去搞

如果,脚本像可执行程序那样,*在系统的PATH里随便找个目录一放就能到处执行*该多好!

早晨爬起来,写了个工具,包括一个批处理文件以及一个python脚本。
*安装方法*:
1. 下载http://www.2maomao.com/blog/wp-content/uploads/exepy.zip
2. 在系统PATH中找个目录,往里一扔就行,我放在了c:\python\scripts(已经加入系统PATH中)

*使用方法*:
此工具为命令行工具
在命令行中,敲入:p epydoc xxx
这样就可以执行c:\python\scripts\下面的epydoc.py了,xxx是参数列表

*注意*:python.exe所在目录要加入到PATH中,通常是c:\python

――――-*实现细节*――――-
批处理文件p.bat:
下载: p.bat<http://www.2maomao.com/blog/wp-content/plugins/coolcode/coolcode.php?p=451&download=p.bat>
@echo off
REM this command file intend to quickly execute python file in the PATH
REM Usage: p xxx, xxx is the name of xxx.py in PATH
python %~dp0\py\exepy.py %1 %2 %4 %5 %6 %7 %8 %9
@echo on

Python脚本(放在p.bat所在的目录的"py"子目录下,可以自己去修改p.bat来自定义目录)
#!/usr/bin/python
import os
import sys
#-----------------------------------------------
def show_help():
    print
    print "  Purpose:   Execute python script in system PATH"
    print "  Usage:     p python_script_name [params]"
    print
#-----------------------------------------------
if len(sys.argv) < 2:
    show_help()
    exit()

script = sys.argv[1]
if len(script) > 3 and script[-3:].lower() != '.py':
    script += '.py'
params = ""
for arg in sys.argv[2:]:
    params += " \"" + arg + "\""
path_str = os.environ['PATH']
paths = path_str.split(';')
for path in paths:
    if len(path) == 0:
        continue
    if path[-1] != '\\':
        path += '\\'

    full_path = path + script
    if os.path.isfile(full_path):
        cmd = "python \"" + full_path + "\"" + params
        os.system(cmd)
        exit()

-- 
http://www.2maomao.com/blog

_______________________________________________
python-chinese
Post: send [email protected]
Subscribe: send subscribe to [email protected]
Unsubscribe: send unsubscribe to  [email protected]
Detail Info: http://python.cn/mailman/listinfo/python-chinese