Importing Python module from Bash

27,918

Solution 1

An easy way to do this is with the "code" module:

python -c "import code; code.interact(local=locals())"

This will drop you into an interactive shell when code.interact() is called. The local keyword argument to interact is used to prepopulate the default namespace for the interpreter that gets created; we'll use locals(), which is a builtin function that returns the local namespace as a dictionary.

Your command would look something like this:

python -c "import mymodule, code; code.interact(local=locals())"

which drops you into an interpreter that has the correct environment.

Solution 2

use a subroutine instead of alias

callmyprogram(){
  python -i -c "import time;print time.localtime()"
}
callmyprogram

Solution 3

Example:

python -c "import time ; print 'waiting 2 sec.'; time.sleep(2); print 'finished' "
Share:
27,918
Morlock
Author by

Morlock

Biologist caught in the data storm. Self-transforming into bioinformatician - GNU/Linux or nothing - Lover of Python - Learning Common Lisp, Perl, Go, Linux sys administration - Working to become a full-fledged programmer -------------------------------------------------- Fastest reply received: 30 seconds!

Updated on February 06, 2020

Comments

  • Morlock
    Morlock over 4 years

    I am launching a Python script from the command line (Bash) under Linux. I need to open Python, import a module, and then have lines of code interpreted. The console must then remain in Python (not quit it). How do I do that?

    I have tried an alias like this one:

    alias program="cd /home/myname/programs/; python; import module; line_of_code"
    

    But this only starts python and the commands are not executed (no module import, no line of code treated).

    What is the proper way of doing this, provided I need to keep Python open (not quit it) after the script is executed? Many thanks!