简体   繁体   中英

How to use python properly to extend cmd.exe functionality

I'm looking for a way to write a few batch scripts to use as custom shell commands using python.

Here's a simple example:

FILENAME: gotofile.bat (put this batch commands file somewhere visible from %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()

Now from a cmd shell type gotofile some_file_you_wish_to_find.ext (pick a file that is not too far away, or else os.walk will take a while)

Assuming it exists, Python should find your file, print where it would like to take you, the cls os.system call will correctly clear your screen but the two other os.system calls don't do anything.

Is there any way of making this work? Or will I have to do this all natively in batch?

Yes, with the changes shown -- you could probably shorten the batch file portion by putting some of the & 's back in.

@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 """

Note: If Python is installed, you should be able to just use python -x "%~f0" %* instead of hard-coding the full path to python.exe .

No.

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")

this should do what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM