running series of interactive shell commands in bash/python/perl script
Question: Currently, I do the following steps:

a. Grep for pid of a process and kill it.

    
    
    ps -aux | grep foo.bar  # process of interest
    kill -9 pid_of_foo.bar  # kill the process
    

b. start virtualenv

    
    
    cd {required_folder}
    sudo virtualenv folder/
    cd {folder2}
    source bin/activate
    

c. Start the manage.py in shell mode

    
    
    cd {required folder}
    sudo python manage.py shell
    

d. In the interactive manage shell, execute the following commands:

    
    
    from core import *
    foo.bar.bz.clear.state()
    exit
    

e. Execute a script

    
    
       /baz/maz/foo
    

In bash we can write down a series of commands, however Is it possible to run
the interactive shell in django using bash and execute commands? I was
wondering if above steps can be scriptified.

Thanks


Answer: You need a script like this one:

    
    
    #!/bin/bash
    
    # kill all foo.bar's instances
    for pid in $(ps -aux | grep foo.bar | grep -v grep | awk '{print $2;}'); do
        kill $pid
    done
    
    # start virtualenv
    cd {required_folder}
    ...
    
    # Start the manage.py in shell mode
    cd {required folder}
    cat << EOF | sudo python manage.py shell
    from core import *
    foo.bar.bz.clear.state()
    exit
    EOF
    
    # Execute a script 
    /baz/maz/foo
    

The key point of the script is HEREDOC python snippet. Take a look at the
example I've just tried in a console:

    
    
    [alex@galene ~]$ cat <<EOF_MARK | python -
    > import sys
    > print "Hello, world from python %s" % sys.version
    > exit
    > EOF_MARK
    Hello, world from python 2.7.6 (default, Nov 22 2013, 22:57:56)
    [GCC 4.7.2 20121109 (ALT Linux 4.7.2-alt7)]
    [alex@galene ~]$ _
    

