Is there a way to compile a Python .py file from the command-line without executing it?
I am working with an application that stores its python extensions in a non-standard path with limited permissions and I'd like to compile the files during installation. I don't need the overhead of Distutils.
The py_compile module provides a function to generate a byte-code file from a source file, and another function used when the module source file is invoked as a script.
python -m py_compile fileA.py fileB.py fileC.py
Yes, there is module compileall. Here's an example that compiles all the .py files in a directory (but not sub-directories):
python -m compileall -l myDirectory
In fact if you're on Linux you may already have a /usr/bin/py_compilefiles command in your PATH. It wraps the the py_compile module mentioned by other people. If you're not on Linux, here's the script code.
$ python -c "import py_compile; py_compile.compile('yourfile.py')"
or
$ python -c "import py_compile; py_compile.compileall('dir')"
In addition to choose the output location of pyc (by #Jensen Taylor's answer),
you can also specify a source file name you like for traceback if you don't want the absolute path of py file to be written in the pyc:
python -c "import py_compile; py_compile.compile('src.py', 'dest.pyc', 'whatever_you_like')"
Though "compileall -d destdir" can do the trick too, it will limit your working directory sometimes.
For example, if you want source file name in pyc to be "./src.py", you have to move working directory
to the folder of src.py, which is undesirable in some cases, then run something like "python -m compileall -d ./ ."
I would say something like this, so you can compile it to your chosen location:
import py_compile
py_compile(filename+".py",wantedlocation+wantedname+".pyc")
As I have now done in my Python project on github.com/lolexorg/Lolex-Tools
Related
I have installed python and I have a file Wifite.py that exists in my current directory.
But whenever I try to run the Wifite2.py file I receive this error:
‘python’: No such file or directory
jarvus#jarvus:~/wifite2$ ls
bin PMKID.md setup.py wordlist
Dockerfile README.md tests wordlist-
EVILTWIN.md reaver-wps-fork-t6x TODO.md
LICENSE runtests.sh wifite
MANIFEST.in setup.cfg Wifite.py
jarvus#jarvus:~/wifite2$ ./Wifite.py
/usr/bin/env: ‘python’: No such file or directory
What changes should be made to get ./Wifite.py working?
The workaround I got is using:
python3 Wifite.py
But I'm looking for alternatives.
This message:
/usr/bin/env: ‘python’: No such file or directory
suggests that the hashbang in your script looks like this:
#!/usr/bin/env python
Since running the script explicitly with python3 worked OK, it sounds like you're on a distro where by default you only have python3 and no python. As other answers suggest, you may install python-is-python3 (which basically creates a python symlink pointing to python3). If you don't wish to do that, then just adjust the script's hashbang so that /usr/bin/env looks for python3:
#!/usr/bin/env python3
Seems you don't have python2 installed but only python3 but it is not registered as plain python.
Try
which python
which python2
which python3
If only the last command runs without error you can try to link python3 to python with
sudo apt-get install python-is-python3
Use shebangs!
In the first line of your script write the python interpretor path.
#! /usr/bin/python
Then chmod +x your file on shell. That will make it executable. And you can directly run it.
Try running python3 Wifite2.py from the directory where the file exists.
I don't really know how to ask this question but I can describe what I want to achieve. I would update any edits that would be suggested.
I have a python module that makes use of some command line arguments. Using the module requires some initial setup outside of the python interpreter. The python file that does the setup runs fine, but the problem is that I have to dig through the python installation to find where that file is located i.e. I have to do python full-path-to-setup-script.py -a argA -b argB etc.I would like to call the setup script like this
some-setup-command -a argA -b argB etc.
I want to achieve something like
workon environmnent_name as in the virtualenv module or
pipenv install as in the pipenv module.
I know both of the above commands call a script of some kind (whether bash or python). I've tried digging through the source codes of virtualenv and pipenv without any success.
I would really appreciate if someone could point me to any necessary resource for coding such programs.
If full-path-to-setup-script.py is executable and has a proper shebang line
#! /usr/bin/env python
then you can
ln -s full-path-to-setup-script.py ~/bin/some-command
considering ~/bin exists and is in your PATH,
and you'll be able to invoke
some-command -a argA -b argB
It's a bit difficult to understand what you're looking for, but python -m is my best guess.
For example, to make a new Jupyter kernel, we call
python -m ipykernel arg --option --option
Where arg is the CLI argument and option is a CLI option, and ipykernel is the module receiving the args and options.
Commands that are callable from the command prompt are located in one of the directories in your system's PATH variable. If you are on Windows, you see the locations via:
echo %PATH%
Or if you want a nicer readout:
powershell -c "$env:path -split(';')"
One solution is to create a folder, add it to your system's PATH, and then create a callable file that you can run. In this example we will create a folder in your user profile, add it to the path, then create a callable file in that folder.
mkdir %USERPROFILE%\path
set PATH=%PATH%%USERPROFILE%\path;
setx PATH %PATH%
In the folder %USERPROFILE%\path, we create a batch file with following content:
# file name:
# some-command.bat
#
python C:\full\path\to\setup-script.py %*
Now you should be able to call
some-command -a argA -b argB
And the batch file will call python with python script and pass the arguments you added.
Looking at the above answers, I see no one has mentioned this:
You can of course compile the python file and give executable permissions with
chmod +x filename.py
and then run it as
./filename.py -a argA -b argB ...
Moreover, you can also remove the extention .py (since it is an executable now) and then run it only as
./filename -a argA -b argB ...
How can I run a python script with my own command line name like myscript without having to do python myscript.py in the terminal?
Add a shebang line to the top of the script:
#!/usr/bin/env python
Mark the script as executable:
chmod +x myscript.py
Add the dir containing it to your PATH variable. (If you want it to stick, you'll have to do this in .bashrc or .bash_profile in your home dir.)
export PATH=/path/to/script:$PATH
The best way, which is cross-platform, is to create setup.py, define an entry point in it and install with pip.
Say you have the following contents of myscript.py:
def run():
print('Hello world')
Then you add setup.py with the following:
from setuptools import setup
setup(
name='myscript',
version='0.0.1',
entry_points={
'console_scripts': [
'myscript=myscript:run'
]
}
)
Entry point format is terminal_command_name=python_script_name:main_method_name
Finally install with the following command.
pip install -e /path/to/script/folder
-e stands for editable, meaning you'll be able to work on the script and invoke the latest version without need to reinstall
After that you can run myscript from any directory.
I usually do in the script:
#!/usr/bin/python
... code ...
And in terminal:
$: chmod 755 yourfile.py
$: ./yourfile.py
Another related solution which some people may be interested in. One can also directly embed the contents of myscript.py into your .bashrc file on Linux (should also work for MacOS I think)
For example, I have the following function defined in my .bashrc for dumping Python pickles to the terminal, note that the ${1} is the first argument following the function name:
depickle() {
python << EOPYTHON
import pickle
f = open('${1}', 'rb')
while True:
try:
print(pickle.load(f))
except EOFError:
break
EOPYTHON
}
With this in place (and after reloading .bashrc), I can now run depickle a.pickle from any terminal or directory on my computer.
The simplest way that comes to my mind is to use "pyinstaller".
create an environment that contains all the lib you have used in your code.
activate the environment and in the command window write pip install pyinstaller
Use the command window to open the main directory that codes maincode.py is located.
remember to keep the environment active and write pyinstaller maincode.py
Check the folder named "build" and you will find the executable file.
I hope that this solution helps you.
GL
I've struggled for a few days with the problem of not finding the command py -3 or any other related to pylauncher command if script was running by service created using Nssm tool.
But same commands worked when run directly from cmd.
What was the solution? Just to re-run Python installer and at the very end click the option to disable path length limit.
I'll just leave it here, so that anyone can use this answer and find it helpful.
I would like to run python files from terminal without having to use the command $ python. But I would still like to keep the ability of using '$ python to enter the python interpreter. For example if I had a file named 'foo.py', I can use $ foo.py rather than $ python foo.py to run the file.
How can I do this? Would I need to change the bash file or the paths? And is it possible to have both commands available, so I can use both $ foo.py and $ python foo.py?
I am using ubuntu 14.04 LTS and my terminal/shell uses a '.bashrc' file. I have multiple versions of python installed on my computer, but when running a python file I want the default version to be the latest version of 2.7.x. If what I am asking is not possible or not recommended, I want to at least shorten the command $ python to $ py.
Thank you very much for any help!
Yes you can do this.
1) Ensure that the first line in your file looks like this:
#!/usr/bin/env python
2) Ensure that your files have the execute permission bit set, like this:
$ chmod +x foo.py
3) Now, assuming that your $PATH environment variable is set correctly*, you can run foo.py either way:
$ foo.py
$ python foo.py
* By "correctly", I mean, "to include the directory where your python file lives." In the use case you describe, that probably means "to include the current directory". To do that, edit .bashrc. One possible line to put in .bashrc is: PATH="$PATH":.
sharkbyte,
It's easy to insert '#!/usr/bin/env python' at the top of all your Python files. Just run this sed command in the directory where your Python files live:
sed -i '1 i\#! /usr/bin/env python\n' *.py
The -i option tells sed to do an in-place edit of the files, the 1 means operate only on line 1, and the i\ is the insert command. I put a \n at the end of the insertion text to make the modified file look nicer. :)
If you're paranoid of stuffing up, copy some files to an empty directory first & do a test run.
Also, you can tell sed to make a backup of each original file, eg:
sed -i.bak '1 i\#! /usr/bin/env python\n' *.py
for MS style, or
sed -i~ '1 i\#! /usr/bin/env python\n' *.py
for the usual Linux style.
There are python scripts with command line arguments that I'd like to call from any location on my PC.
The idea is to share the corresponding package with others so they can open up a CMD window and run
python thescript.py arg1 arg2
regardless of their location.
How do I setup the python path/ PATH environment variables?
I've setup a package in site-packages, added that path to $PATH and edited PYTHONPATH to include the module directory (which includes __init__.py), but CMD won't find the relevant scripts.
python: can't open file 'thescript.py': [Errno 2] No such file or directory
Thanks.
Python does not look up scripts on some sort of path.
You have 2 options:
Use the full path:
python /path/to/thescript.py
Place the script in a directory that is on your PATH, make it executable (chmod +x thescript.py) and give it a Shebang line:
#!/bin/env python
The second option is probably preferable. On Windows, you can install pylauncher to support shebang lines; if you use Python 3.3 or newer, it is already included with your Python installation.
Another option would be to create a batch file for each script you care about, and put the batch file somewhere in your PATH, e.g. create a file called thescript.bat containing...
#echo off
the\path\to\python.exe the\path\to\thescript.py %*
...then you can just run...
thescript arg1 arg2
...which is about as terse a syntax as possible.