Execute current file in Vim without shebang - python

Is there a clean alias that I can put in my vimrc that will run the current file using python if there is a python extension?
At the moment I have nnoremap <leader>r :!%:p<Enter> as suggested in this question (when I hit \+r it runs the open file). It works great for bash files, where the convention is to add a shebang line and make the file executable, but for python files it obviously exits 1.
As a workaround I have added a new command - command PyBang :call append(0, "#!/usr/bin/env python") - that adds a python shebang to the top of the file. The problem is that this is not really convention for .py files and making them all executable seems like a lot of effort for some reason.
So I am struggling to write an alias that will run :!%:p<Enter> if there is no extension and prepend python if there is a .py extension on the file in the buffer.
Any ideas are really appreciated.

The easiest way to do this is to use vim's exclamation mark to run shell commands. For instance,
: ! python3 % will run the current file % with python3 outside of vim, in whatever shell you're in.
You can use this in combination with vim scripting to create your own shortcuts for this command.
To combine this with your current bash function, you will need conditional logic in your vim function to detect filetypes (see here and here for how to work with filetypes and their detection)

Related

Running Python program with dot slash: No such file or directory [duplicate]

I have several python scripts which work just fine but one script has (as of this morning) started giving me this error if I try to run it from the bash:
: No such file or directory
I am able to run the 'broken' script by doing python script_name.py and after looking around a bit the general idea that I picked up was that maybe my line ending of the hashbang got changed (silently) so I looked at the line ending of a working script and a broken script via the :set list option in VI as indicated in this question -> View line-endings in a text file
Both files appear to end using the same character (a $) so I am kind of at a loss on how to proceed from here. Specifically, how to actually 'see' the line ending in case the set list was not the right method.
PS: The script is executable and the shebang is in there, I stated that it's just this 1 script that was working fine before the weekend but it started giving me this error as of this morning.
-- edit: --
Running the script through dos2unix does get it working again but I would like to know of any way to visualize the line ending somehow in VI(M) or why Geany somehow converted the line endings in the first place (as I never work on a dos/windows system anyhow).
From the comments above it looks like you have dos line endings, and so the hashbang line is not properly processed.
Line ending style are not shown with :set list in Vim because that option is only used when reading/writing the file. In memory line endings are always that, line-endings. The line ending style used for a file is kept in a Vim per-file option, weirdly called fileformat.
To see/change the line ending style from Vim, you can use the following commands:
:set fileformat
:set ff
It will show dos or unix. You want unix, of course ;-).
To change it quickly you can save the file with:
:w ++ff=unix
Or if you prefer:
:set ff=unix
And then save the file normally.
So see all the gory details just do :help fileformat, :help file-formats and :help fileformats
You can also use the dos2unix command to convert the file format
dos2unix
This helped me to run the python scripts
This normally happens when we open files in windows do changes and save it.
if you open the file locate the ^M characters at the end of every line
Thanks
Personally, I find it kinda wrong using direct path to python interpreter. As you dont use windows platform, you should have program env, usually in /usr/bin (/usr/bin/env). Try using following shebang:
#!/usr/bin/env python
Different distros store python binary in /bin or /usr/bin (or some weird locations), and this one makes your script config-independent (as far as possible, here we have possibility that env is stored elsewhere; still - it is less possible that env is not in /usr/bin than that python is mislocated).
I had similiar problem (if not exactly the same) and that worked for me.
Also, I have both python interpreters (2.7.x and 3.x) installed, so I need to use "python3" argument for env. AFAIR usually distros link different names to different binaries, so "env python" will run python2.7 on my system, "env python3" (also python33, or smth like that) will run p3k, and "env python2" (also python27, etc) will run python 2.7.x. Declaring which version of interpreter should be used seems like a good idea too.
I came across this problem editing my code on Windows, checking it in with git, and checking out and running it on Linux.
My solution was: tell git to Do The Right Thing. I issued this command on the Windows box:
git config --global core.autocrlf true
Modified the files and checked them in; voila, no such problem any more.
As discussed on the Git documentation.

Running a Python script with and without "python" [duplicate]

I have a simple script blah.py (using Python 2):
import sys
print sys.argv[1]
If I execute my script by:
python c:/..../blah.py argument
It prints argument but if I execute script by:
blah.py argument
error occurs:
IndexError...
So arguments do not pass to script.
python.exe in PATH. Folder with blah.py also in PATH.
python.exe is default program to execute *.py files.
What is the problem?
When you execute a script without typing "python" in front, you need to know two things about how Windows invokes the program. First is to find out what kind of file Windows thinks it is:
C:\>assoc .py
.py=Python.File
Next, you need to know how Windows is executing things with that extension. It's associated with the file type "Python.File", so this command shows what it will be doing:
C:\>ftype Python.File
Python.File="c:\python26\python.exe" "%1" %*
So on my machine, when I type "blah.py foo", it will execute this exact command, with no difference in results than if I had typed the full thing myself:
"c:\python26\python.exe" "blah.py" foo
If you type the same thing, including the quotation marks, then you'll get results identical to when you just type "blah.py foo". Now you're in a position to figure out the rest of your problem for yourself.
(Or post more helpful information in your question, like actual cut-and-paste copies of what you see in the console. Note that people who do that type of thing get their questions voted up, and they get reputation points, and more people are likely to help them with good answers.)
Brought In From Comments:
Even if assoc and ftype display the correct information, it may happen that the arguments are stripped off. What may help in that case is directly fixing the relevant registry keys for Python. Set the
HKEY_CLASSES_ROOT\Applications\python26.exe\shell\open\command
key to:
"C:\Python26\python26.exe" "%1" %*
Likely, previously, %* was missing. Similarly, set
HKEY_CLASSES_ROOT\py_auto_file\shell\open\command
to the same value. See http://eli.thegreenplace.net/2010/12/14/problem-passing-arguments-to-python-scripts-on-windows/
HKEY_CLASSES_ROOT\Applications\python.exe\shell\open\command The registry path may vary, use python26.exe or python.exe or whichever is already in the registry.
HKEY_CLASSES_ROOT\py_auto_file\shell\open\command
you should make the default application to handle python files be python.exe.
right click a *.py file, select "Open With" dialog. In there select "python.exe" and check "always use this program for this file type" (something like that).
then your python files will always be run using python.exe
Additionally, if you want to be able to run your python scripts without typing the .py (or .pyw) on the end of the file name, you need to add .PY (or .PY;.PYW) to the list of extensions in the PATHEXT environment variable.
In Windows 7:
right-click on Computer
left-click Properties
left-click Advanced system settings
left-click the Advanced tab
left-click Environment Variables...
under "system variables" scroll down until you see PATHEXT
left-click on PATHEXT to highlight it
left-click Edit...
Edit "Variable value" so that it contains ;.PY (the End key will skip to the end)
left-click OK
left-click OK
left-click OK
Note #1: command-prompt windows won't see the change w/o being closed and reopened.
Note #2: the difference between the .py and .pyw extensions is that the former opens a command prompt when run, and the latter doesn't.
On my computer, I added ;.PY;.PYW as the last (lowest-priority) extensions, so the "before" and "after" values of PATHEXT were:
before: .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
after .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY;.PYW
Here are some instructive commands:
C:\>echo %pathext%
.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY;.PYW
C:\>assoc .py
.py=Python.File
C:\>ftype Python.File
Python.File="C:\Python32\python.exe" "%1" %*
C:\>assoc .pyw
.pyw=Python.NoConFile
C:\>ftype Python.NoConFile
Python.NoConFile="C:\Python32\pythonw.exe" "%1" %*
C:\>type c:\windows\helloworld.py
print("Hello, world!") # always use a comma for direct address
C:\>helloworld
Hello, world!
C:\>
How to execute Python scripts in Windows?
You could install pylauncher. It is used to launch .py, .pyw, .pyc, .pyo files and supports multiple Python installations:
T\:> blah.py argument
You can run your Python script without specifying .py extension if you have .py, .pyw in PATHEXT environment variable:
T:\> blah argument
It adds support for shebang (#! header line) to select desired Python version on Windows if you have multiple versions installed. You could use *nix-compatible syntax #! /usr/bin/env python.
You can specify version explicitly e.g., to run using the latest installed Python 3 version:
T:\> py -3 blah.py argument
It should also fix your sys.argv issue as a side-effect.
I encountered the same problem but in the context of needing to package my code for Windows users (coming from Linux).
My package contains a number of scripts with command line options.
I need these scripts to get installed in the appropriate location on Windows users' machines so that they can invoke them from the command line.
As the package is supposedly user-friendly, asking my users to change their registry to run these scripts would be impossible.
I came across a solution that the folks at Continuum use for Python scripts that come with their Anaconda package -- check out your Anaconda/Scripts directory for examples.
For a Python script test, create two files: a test.bat and a test-script.py.
test.bat looks as follows (the .bat files in Anaconda\Scripts call python.exe with a relative path which I adapted for my purposes):
#echo off
set PYFILE=%~f0
set PYFILE=%PYFILE:~0,-4%-script.py
"python.exe" "%PYFILE%" %*
test-script.py is your actual Python script:
import sys
print sys.argv
If you leave these two files in your local directory you can invoke your Python script through the .bat file by doing
test.bat hello world
['C:\\...\\test-scripy.py', 'hello', 'world']
If you copy both files to a location that is on your PATH (such as Anaconda\Scripts) then you can even invoke your script by leaving out the .bat suffix
test hello world
['C:\\...Anaconda\\Scripts\\test-scripy.py', 'hello', 'world']
Disclaimer: I have no idea what's going on and how this works and so would appreciate any explanation.
On Windows,
To run a python module without typing "python",
--> Right click any python(*.py) file
--> Set the open with property to "python.exe"
--> Check the "always use this program for this file type"
--> Append the path of python.exe to variable environment e.g. append
C:\Python27 to PATH environment variable.
To Run a python module without typing ".py" extension
--> Edit PATHEXT system variable and append ".PY" extension to the list.
Can you execute python.exe from any map?
If you do not, chek if you have proper values for python.exe in PATH enviroment
Are you in same directory than blah.py. Check this by issuing command -> edit blah.py and check if you can open this file
EDIT:
In that case you can not. (python arg means that you call python.exe whit some parameters which python assume that is filename of script you want to run)
You can create bat file whit lines in your path map and run .bat file
Example:
In one of Path maps create blah.py.bat
Edit file and put line
python C:\Somedir\blah.py
You can now run blah.py from anywere, becuase you do not need to put .bat extention when running bat files
Found an incredibly useful answer here: How to run different python versions in cmd?
I would suggest using the Python Launcher for Windows utility that introduced was into Python 3.3 a while ago. You can also manually download and install it directly from the author's website for use with earlier versions of Python 2 and 3.
Regardless of how you obtain it, after installation it will have associated itself with all the standard Python file extensions (i.e. .py, .pyw, .pyc, and .pyo files). You'll not only be able to explicitly control which version is used at the command-prompt, but also on a script-by-script basis by adding Linux/Unix-y shebang #!/usr/bin/env pythonX comments at the beginning of your Python scripts.
As J.F. Sebastian suggests, Python Launcher for Windows is the best and default choice for launching different version of Python in Windows. It used to be a third-party tool, but now it is officially supported since Python 3.3.
New in version 3.3.
The Python launcher for Windows is a utility which aids in the location and execution of different Python versions. It allows scripts (or the command-line) to indicate a preference for a specific Python version, and will locate and execute that version.
This is a great tool just use it!
Simply run the command:
C:>python .\file_name.py
Assuming the file name is within same folder and Python has already been added to environment variables.

When using Python Windows Launcher, is there any way to prevent having to type full path?

In Windows 8, I often use the Python Windows Launcher like
py C:/long/long/long/long/long/path/to/prog.py ...
Is there any way to set some environment setting, such as PATH or PYTHONPATH etc, to prevent having to type the full path to prog.py?
From my basic knowledge/research, PATH only helps with the py part of the command line and PYTHONPATH only helps with imports within prog.py, so how do I deal with the path to prog.py itself??
Notes:
I cannot modify the code, not even the "shebang" line, since it is needed to work on other platforms.
I cannot cd to the directory containing the programs to run them, because the programs will do something based on the directory they're run in (they'll modify the files in the directory they're run in).
I know that if I associate .py extension with the Python Windows Launcher, then I can run prog.py as the first item in the command line, and thus use PATH, but currently my .py extension is associated with my favorite editor and I'd like to keep it that way if possible (so I can double-click any Python file in Windows Explorer and edit it).
However, if someone suggests a solution where I can have a different association for Windows Explorer versus the command line, then that could be a potential solution! (i.e. in Windows Explorer, .py opens with the editor, while on command line, .py runs with Python Windows Launcher)
Add your long path to PYTHONPATH, then invoke your program as such:
python -m prog
Python will search for a module called prog and then run it as the main module.
Answer to my own question: Actually, I'm so silly. I could just set a variable for each program path (there are only a few programs paths), i.e.. prog=C:/long/path/to/prog.py and then do py %prog% .... I guess I figured out an answer to my own question that was acceptable to me.
Update: I just found something even better. I can do
doskey prog=py C:/long/path/to/prog.py $*
and then simply prog ... afterward
Now I just have to do some crazy stuff to get the doskey command into a file that will be run every time I start a console, as described here: https://stackoverflow.com/a/21040825/5182136

Unable to find and execute python script in shell [duplicate]

I have several python scripts which work just fine but one script has (as of this morning) started giving me this error if I try to run it from the bash:
: No such file or directory
I am able to run the 'broken' script by doing python script_name.py and after looking around a bit the general idea that I picked up was that maybe my line ending of the hashbang got changed (silently) so I looked at the line ending of a working script and a broken script via the :set list option in VI as indicated in this question -> View line-endings in a text file
Both files appear to end using the same character (a $) so I am kind of at a loss on how to proceed from here. Specifically, how to actually 'see' the line ending in case the set list was not the right method.
PS: The script is executable and the shebang is in there, I stated that it's just this 1 script that was working fine before the weekend but it started giving me this error as of this morning.
-- edit: --
Running the script through dos2unix does get it working again but I would like to know of any way to visualize the line ending somehow in VI(M) or why Geany somehow converted the line endings in the first place (as I never work on a dos/windows system anyhow).
From the comments above it looks like you have dos line endings, and so the hashbang line is not properly processed.
Line ending style are not shown with :set list in Vim because that option is only used when reading/writing the file. In memory line endings are always that, line-endings. The line ending style used for a file is kept in a Vim per-file option, weirdly called fileformat.
To see/change the line ending style from Vim, you can use the following commands:
:set fileformat
:set ff
It will show dos or unix. You want unix, of course ;-).
To change it quickly you can save the file with:
:w ++ff=unix
Or if you prefer:
:set ff=unix
And then save the file normally.
So see all the gory details just do :help fileformat, :help file-formats and :help fileformats
You can also use the dos2unix command to convert the file format
dos2unix
This helped me to run the python scripts
This normally happens when we open files in windows do changes and save it.
if you open the file locate the ^M characters at the end of every line
Thanks
Personally, I find it kinda wrong using direct path to python interpreter. As you dont use windows platform, you should have program env, usually in /usr/bin (/usr/bin/env). Try using following shebang:
#!/usr/bin/env python
Different distros store python binary in /bin or /usr/bin (or some weird locations), and this one makes your script config-independent (as far as possible, here we have possibility that env is stored elsewhere; still - it is less possible that env is not in /usr/bin than that python is mislocated).
I had similiar problem (if not exactly the same) and that worked for me.
Also, I have both python interpreters (2.7.x and 3.x) installed, so I need to use "python3" argument for env. AFAIR usually distros link different names to different binaries, so "env python" will run python2.7 on my system, "env python3" (also python33, or smth like that) will run p3k, and "env python2" (also python27, etc) will run python 2.7.x. Declaring which version of interpreter should be used seems like a good idea too.
I came across this problem editing my code on Windows, checking it in with git, and checking out and running it on Linux.
My solution was: tell git to Do The Right Thing. I issued this command on the Windows box:
git config --global core.autocrlf true
Modified the files and checked them in; voila, no such problem any more.
As discussed on the Git documentation.

Compiling Python

How can I compile and run a python file (*.py extension)?
python yourfile.py
You have to have python installed first. It will automatically compile your file into a .pyc binary, and then run it for you. It will automatically recompile any time your file changes.
http://www.python.org/download/
Python compiles its files to bytecode before executing them. That means you have to have a Python interpreter installed on the target machine.
If you don't want to install Python on the target machine use py2exe, py2app or something similar.
If you just want to compile sources, without running them, you can do this
compileall.py <directory>
this command will compile python code in that directory recursively
compileall script is usually located in directory like
/usr/local/lib/python2.6
i.e. <prefix>/lib/python2.6 (or similar, depending on prefixes set a python configuration)
As Lulu suggests, you should make sure that resulting .pyc and .pyo files are executable by the users you care about.
compileall can also be used as a module
import compileall
compileall.compile_dir(path)
Python is an interpreted language, so you don't need to compile it; just to run it. As it happens, the standard version of python will compile this to "bytecode", just like Java etc. does, and will save that (in .pyc files) and run it next time around, saving time, if you haven't updated the file since. If you've updated the file, it will be recompiled automatically.
You can also run python with a -O flag, which will generate .pyo files instead of .pyc. I'm not sure it makes much difference. If speed is important, use psyco.
And yes, on Unix (including Linux, BSD, and Mac OS X, or in a unix shell on windows) you can use a shebang line at the top of the file to make the file automatically run using python. On windows, the equivalent is to associate .py files with python.exe, and then make sure your PATHEXT environment variable includes ".PY" extensions.
However, for windows, you more likely want to write a gui program in python (possibly using PyQT4 and ERIC4) which has a .pyw file as its main script, and has .pyw associated with pythonw (which comes with python on windows). This will let you run python scripts on windows just like other GUI programs. For publishing and distribution, you probably want to compile to an executable file using something like py2exe, as others mentioned.
To add to Paul McMillan's answer, if you are on Windows and you have Python installed, then any files ending with the extension ".py" should be associated with the python executable, allowing you to run it like so:
> myfile.py
In *nix, you can begin the file with #!/usr/bin/python and run it like so:
$ ./myfile.py
In *nix systems, if the first two characters of a file are #! then it will execute the file with the specified executable, which I set here to be /usr/bin/python.
If you want to transform a python source file into a double-clickable .exe on windows, you can use py2exe, which can help you build an easy to distribute package.
On most Unix-like systems, you can use the shebang to tell the operating system which interpreter should be called. You simply put
#!/path/to/python
in the first line of your file, where of course you have to replace "/path/to/" with the path you have on your system. In most cases this would be "/usr/bin/python" or "/usr/local/bin/python". On unix systems you could also look for the path with
"#!usr/bin/env python"
or invoke the command
which python
to find the path.
You can then run your program with the command
./yourprogram.py
If it tells you that you do not have permission to do so, you have to use the command
chmod a+x yourprogram.py
Answer for Windows
first you must install python
then set path variable
after that write your python program and save
think there is a python program that name "hello.py"
open cmd.exe
then goto the path that you saved your "hello.py" file,
and then type python hello.py and press enter key.
now the python code is automatically compile and show the result.

Categories