0

I am new to Python, could someone please let me know if we can register our python script to work as one of the command of cmd.exe, I am not asking about parsing or accepting command line arguements using argparse, etc..

Lets say I have a SearchDir.py file, to run it from cmd prompt I have to do "python SearchDir.py", so is there any way to simply do "SearchDir" and it should act as one of the command of cmd.exe

Prabhakar
  • 402
  • 6
  • 20
  • write a cmd/bat file containing "python SearchDir.py"? – Nikita Kipriyanov Dec 06 '15 at 17:23
  • Are you talking about [File associations](http://windows.microsoft.com/en-us/windows/change-file-open-program#1TC=windows-7)? – CristiFati Dec 06 '15 at 17:32
  • @NikitaKipriyanov A good idea but I am sure there would be a more better approach to it. Thanks – Prabhakar Dec 06 '15 at 20:42
  • @CristiFati No I am not talking about File associations – Prabhakar Dec 06 '15 at 20:42
  • Allright then. It's just that after associating a file(extension) with an executable, when typing the file name in the command prompt window, that executable is called with the file as the 1st argument. That's what I understood you need. Probably I've got it wrong. – CristiFati Dec 06 '15 at 22:46

1 Answers1

0

Yes, it is possible (if I have understood you correctly. The question was a bit unclear)

The first thing you need to do is to add a shebang to the top of your script: https://en.wikipedia.org/wiki/Shebang_(Unix). I see you mentioned cmd.exe so I assume you need this to work on Windows? In that case you should read https://docs.python.org/3/using/windows.html#shebang-lines as well

On unix hosts, the second thing we need to do is set our file as executable with chmod +x <filename>. I try to stay away from Windows, but from what I remember this is not relevant on Windows.

Last you need to place the script in a folder referenced by your $PATH-variable

The script will now be accessible as SearchDir.py from cmd.exe or a unix shell. If you want to omit the ".py"-part you simply rename the file to just "SearchDir"

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
liasis
  • 96
  • 8
  • According to the documentation I listed, yes: «To allow shebang lines in Python scripts to be portable between Unix and Windows, this launcher supports a number of ‘virtual’ commands to specify which interpreter to use.» – liasis Dec 06 '15 at 18:40
  • @liasis Thanks a lot liasis. Python Launcher is available from python 3.0, so now I can execute SearchDir.py but renaming the file to SearchDir is not working. One way is to add .py in PATHEXT, but in my case this utility will be used by many users and manually adding .py to PATHEXT is not a good option. – Prabhakar Dec 06 '15 at 20:40