How to import a module at each execution of python? - python

I need to run the command import numpy as np each time I run python. How to automatize it in linux. In other words, how do load a module each time python is launch with having to manually call it?

The -i flag can help with that. See man python.
-i When a script is passed as first argument or the -c option is
used, enter interactive mode after executing the script or the
command. It does not read the $PYTHONSTARTUP file. This can be
useful to inspect global variables or a stack trace when a script
raises an exception.
So the below does what you want it to. Note that the -i flag needs to precede the -c otherwise it doesn't work.
python -i -c 'import numpy'

Related

How to run a Python script setting the location of the modules in the shell?

I would like to run a Python script setting in the shell where the interpreter must look for the modules.
Suppose that myscript.py contains only:
import mymodule ; mymodule.myfunction()
But mymodule is in /home/user/hello, whereas myscript.py is, say, in /home/user/Desktop. I want to run on a terminal something like:
$ python /home/user/Desktop/myscript.py LOCATION_OF_THE_MODULES=/home/user/hello.
Would it be possible? I think that an alternative solution is to define the location in the import statement from the code, but this is not what I am looking for. I want to set the location through a variable in the shell.
So, I've been exploring a little your question, turns out this isn't a Python question but a "prompt" question, because indeed there is a way to do that but, since Python can't hop into interactive from script, we can't make it using Python only, but the Python interactive command have some extra options we can use
see:
python3 -h
for more info.
Specifically there are 2 options that are interesting, -i and -c which stands for interactive mode and command string respectively, that way we can load the modules with -c and hop into interactive with -i, like so:
python3 -i -c "import os"
Obviously, we need to make it more advanced so it can load multiple modules without Python scripting, then we will be needing to make the actual command to run Python and load the scripts you want, there is a problem tho, since we need to issue a command to be able to load all the modules you want in a folder it might create incompatibilities with prompts since not all prompts have the same syntax. There might be another low-level answer to this problem but I couldn't get to it, however, I will leave a Bash Script for reference so you can use it and/or edit it so it works best with your prompt.
FINAL_VAR=""
cd $1
for f in *.py; do
FINAL_VAR+="import ${f%.py}"$'\n'
done
python3 -i -c "$FINAL_VAR"
Usage steps:
Copy and save the script
Give it run permissions (chmod +x file_name.sh)
Run it this way: ./file_name.sh "/full/path/to/your/modules"
It will load all the .py files and will hop into an interactive Python shell for your use
Note: You might want to change the last line so it works accordingly to your Python installation

What is the meaning of command line options for python from the windows command prompt (example: -i, -m)

When running python scripts from the command line, sometimes one has to use options like:
script.py
python script.py
python -m script.py
python -i script.py
What do these options do? Where can I find a full list of these options?
I'm asking because I wrote a gui using tkinter, and when I run it using either of the first two methods above I get an ImportError for tkinter, but the -i option works fine. Can I write a python script that defaults to some option (-i) when it is run?
EDIT: Here is the traceback regarding my ImporError:
it gives the file name and then:
import tkinter
ImportError: No module named tkinter
I am using python 3.5.2, and this error doesn't appear if I use
python -i script.py
You can get a list of all the python command flags and what they do by typing
python --help
In the case of tkinter, you need to run with the -i flag because it will run in "interactive mode". This allows the windowed application to launch. The help says it best
-i : inspect interactively after running script; forces a prompt even
if stdin does not appear to be a terminal; also PYTHONINSPECT=x
Meanwhile -m launches a module as if it were a script.
-m mod : run library module as a script (terminates option list)

Unset or remove most recent like of .bash_history from within Python script

The Issue
I have a Python script that when I run it from the command line I do not want to record anything within .bash_history.
The reason for this is that the script uses the Python argparse library which allows me to pass in arguments to the python code directly from the command line.
For example I could write the script so that it would use "123456" as a value in the script:
$ ./scriptname.py -n 123456
The issue is that I don't want the value 123456 stored in .bash_history. In fact, I'd rather the entire command was never stored into the .bash_history file in the first place.
What I've Tried
Subprocess & history -c
I've added the subprocess library to the top of my script and then included this directly after to attempt to proactively clear the current history of the shell I am working in:
subprocess.call("history -c", shell=True)
Theoretically this should clear the history of the current shell. I don't see errors from this so I'm assuming that it runs in some other shell. When I run it outside of the script (directly after running the command to invoke the script) it works properly.
Subprocess & unset HISTFILE
I have also used subprocess with the following with no success:
subprocess.call("unset HISTFILE", shell=True)
os.system & history -c
I've also used the os library for Python and included the following in the script:
os.system("history -c")
os.system and unset HISTFILE
I've also tried unset HISTFILE with os.system to no avail.
os.system("unset HISTFILE")
Preferred Solution Characteristics
I realize that I could simply type in unset HISTFILE or history -c after using the command. But I want this to be as much as possible a self-contained script.
Ideally the solution would prevent the ./scomescript.py command from ever being recorded within .bash_history.
I need this script to output text to the terminal based on the input so I can't close the terminal immediately afterwards either.
I imagine there must be a way to do this from within the python script itself - this is my preference.
This really isn't very feasible... Adding the entry to the history file is performed by the interactive shell, and it occurs after the command has completed and the parent shell exits. It is, strictly speaking, possible, if you were to make your python program execute spawn a hacky background process that did something like read the history file in a loop re-writing it. I really can't advocate anything like this, but you could append your script with something like:
os.system("nohup bash -ic 'while :; do read -d \"\" history < \"$HISTFILE\"; echo \"$history\" | sed -e\"s#^%s.*##\" -e\"/^$/d\" > \"$HISTFILE\"; sleep 1; done &' >/dev/null 2>&1" % sys.argv[0])
I think a much better way to accomplish your goal of not recording any arguments would be to use something like var = raw_input("") instead of passing sensitive argument on the command line.
You could also perhaps create a shell function to wrap your script, something like my_script(){ set +o history; python_script.py "$#; set -o history ;}?

Ansicon doesn't install from python but only from cmd

I'm trying to install ansicon on Windows 8.1. I extracted the files and got to the level that I need to call ansicon -i. When I type this in my cmd and run python scripts that works great but when I call t from python by os.system('ansicon -i') that doesn't work and seems like it doesn't have any influence on the cmd.
Why os.system('ansicon -i') doesn't work and what alternative method can I use from within python?
First off, it’s not the -i flag that really does the work. -i only tells it to add itself to AutoRun. The -p flag that -i implies is what really does the work: -p tells it to inject a DLL into the parent process, and therein lies the problem: when you use os.system, you spawn a shell, which then runs the command you give it. But then you have Python running cmd running ansicon, and ansicon will inject into cmd, and then cmd, having finished its work, will exit.
Rather than using os.system, use the subprocess module, e.g.:
subprocess.check_call(['ansicon', '-p'])
The subprocess module (unlike os.system) will execute the command directly without a shell in-between (unless you pass shell=True). Then Python will spawn ansicon, and ansicon will inject into Python, as desired.
That said, rather than having ansicon inject itself into Python, Python could probably just load the DLL itself, avoiding some hardship:
import sys
import math
import ctypes
bitness = 1 << round(math.log2(round(math.log2(sys.maxsize + 1))))
ctypes.WinDLL('ANSI{}.DLL'.format(bitness))

How to start a Python ipython shell, automatically run inside it a few commands, and leave it open?

I tried
echo "print 'hello'" | ipython
Which runs the command but ipython immediately exits afterwards.
Any ideas? Thanks!
Edit:
I actually need to pass the command into the interactive Django shell, e.g.:
echo "print 'hello'" | python manage.py shell
so the -i switch gimel suggested doesn't seem to work (the shell still exits after execution)
Use the same flag used by the standard interpreter, -i.
-i
When a script is passed as first argument or the -c option is used, enter interactive mode after executing the script or the command, even when sys.stdin does not appear to be a terminal. The PYTHONSTARTUP file is not read.
A Linux example, using the -c command line flag:
$ ipython -i -c 'print "hello, ipython!"'
hello, ipython!
In [2]: print "right here"
right here
In [3]:
Try using the ipy_user_conf.py inside your ~/.ipython
I'm not sure of ipython but the basic python interpreter has a command line parameter to give you the prompt after it executes the file you've given it. I don't have an interpreter handy to tell you what it is but you can get it using python --help. It should do exactly what you want.
Running a custom startup script/profile script with the Django shell was marked as closed: wontfix.
However, there is a shell_plus Django extension discussed in that ticket which seems to do what you want. I haven't had a chance to check it out, but it looks like at the very least it can run a load to auto import all the models of all installed apps (which I usu. find myself doing).
Shell plus.py in django-command-extensions on Google Code
django-command-extensions homepage on Google Code
django_extensions on Github

Categories