views:

116

answers:

4

Question: In command line, how do I call a python script with out having to type "python" before the script? is this even possible?


Info:

I wrote a handy script for accessing sqlite databases from command line, but I kind of don't like having to type "python SQLsap args" and would rather just type "SQLsap args". I don't know if this is even possible, but it would be good to know if it is. For more than just this program.

+11  A: 

You can prepend a shebang on the first line of the script:

#!/usr/bin/env python

This will tell your current shell which command to feed the script into.

efritz
Also, remember to mark your file as executable. (`chmod +x SQLsap` on POSIX OSs.)
Mike DeSimone
ah, so that's what that does. I've seen that before but never known. Thanks!
Narcolapser
Also, I'd like to note that /usr/bin/env is itself a program. It is used to determine *where a specific executable is. If you know where your python interpreter is (/usr/bin/python, for example), you could simply substitute the shebang to read: #! /usr/bin/python. This goes as well for any executable command - perl, python, bash, etc.
efritz
+3  A: 

You want a shebang. #!/path/to/python. Put that on the first line of your python script. The #! is actually a magic number that tells the operating system to interpret the file as a script for the program named. You can supply /usr/bin/python or, to be more portable, /usr/bin/env python which calls the /usr/bin/env program and tells it you want the system's installed Python interpreter.

You'll also have to put your script in your path, unless you're okay with typing ./SQLsap args.

Nathon
+2  A: 

Assuming this is on a unix system, you can add a "shebang" on the top of the file like this:
#!/usr/bin/env python

And then set the executable flag like this:
chmod +x SQLsap

baloo
+1  A: 

On Windows or DOS you can come close by putting your python code into a .BAT file like this.

rem = ''' this line interpreted by BAT and PYTHON
@REM BAT-ONLY code begins now inside PYTHON comment
@echo off
python "%~dpnx0" %*
goto :eof
@REM CMD-ONLY code ends
'''

import sys
print sys.path

Unfortunately, I can't get rid of the first line message on the output, but you could always change the text after ''' to be something like the application's name and people wouldn't notice.

Ideally, you wouldn't put lots of Python code in the .BAT file but would import a .py file and then run its .__main__ method.

Michael Dillon