0

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

这是一个简单的例子:

文件名: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调用不做任何事情。

有什么办法可以使这项工作?还是我必须在本地批量完成这一切?

4

2 回答 2

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.

于 2013-10-22T21:28:11.887 回答
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")

这应该做你想做的。

于 2013-10-22T19:28:40.460 回答