如何正确使用python来扩展cmd.exe功能

时间:2013-10-22 18:58:13

标签: python batch-file cmd

我正在寻找一种方法来编写一些批处理脚本,以便使用python作为自定义shell命令。

这是一个简单的例子:

FILENAME:gotofile.bat (将此批处理命令文件放在%PATH%可见的位置)

@setlocal enableextensions & "C:/Python27/python.exe" -x "%~f0" %* & goto :EOF 

# Looks for a file on disk and take me there
import sys
import os
if len(sys.argv) == 2:
    for root, dirnames, filenames in os.walk(os.getcwd()):
        for filename in filenames:
            if filename == sys.argv[1]:
                print 'TAKING YOU TO: %s'%root
                os.system('cls')
                os.system('title %s'%root)
                os.system('cd %s'%root)
                quit()

现在从cmd shell类型 gotofile some_file_you_wish_to_find.ext (选择一个不太远的文件,否则os.walk需要一段时间)

假设它存在,Python应该找到你的文件,打印它想带你去的地方,cls os.system调用将正确地清除你的屏幕,但另外两个os.system调用什么都不做。< / p>

有没有办法让这项工作?或者我是否必须批量生产这些?

2 个答案:

答案 0 :(得分:2)

是的,如果显示更改,您可以通过将一些&重新放入来缩短批处理文件部分。

@echo off
rem = """
setlocal enableextensions
set PYTHON="C:/Python27/python.exe"
%PYTHON% -x "%~f0" %*
goto endofPython """

# Your python code goes here ..

if __name__ == "__main__":
    # Looks for a file on disk and take me there
    import sys
    import os
    if len(sys.argv) == 2:
        for root, dirnames, filenames in os.walk(os.getcwd()):
            for filename in filenames:
                if filename == sys.argv[1]:
                    print 'TAKING YOU TO: %s' % root
                    command = '&'.join(['cls',
                                        'title %s' % root,
                                        'cd %s' % root,
                                        'cmd /k'])
                    os.system(command)

rem = """
:endofPython """

注意:如果安装了Python,您应该只能使用python -x "%~f0" %*而不是硬编码python.exe的完整路径。

答案 1 :(得分:1)

没有

for /f "delims==" %%i in ('dir "%SystemDrive%" /s /b^|find "%~1" /i') do (echo TAKING YOU TO: %%i&timeout /nobreak 1 >nul&cls&title %%~dpi&cd /d "%%~dpi")

这应该做你想要的。

相关问题