pythonbashsubprocess

Python subprocess.call a bash alias


I have an alias in my .bashrc that calls some other script, passing it specific command-line arguments.

I want to write a python script that would call this alias every few minutes so I can have a shell open with updated stats.

However, subprocess.call("myAlias"), tried like so, fails:

from subprocess import call

def callAlias():
    call("myAlias")

callAlias()

How can I make Python use the alias from my .bashrc?


Solution

  • Update: Thanks for the upvotes for this hack to workaround the problem, I'm glad it's useful. But a much better answer is tripleee's.


    If the alias you require is defined in ~/.bashrc, then it won't get run for a few reasons:

    1. You must give the shell keyword arg:

      subprocess.call('command', shell=True)
      

      Otherwise your given command is used to find an executable file, rather than passed to a shell, and it is the shell which expands things like aliases and functions.

    2. By default, subprocess.call and friends use the /bin/sh shell. If this is a Bash alias you want to invoke, you'll need to tell subprocess to use bash instead of sh, using the executable keyword arg:

      subprocess.call('command', shell=True, executable='/bin/bash')
      
    3. However, /bin/bash will not source ~/.bashrc unless started as an 'interactive' shell (with -i.) Unfortunately, you can't pass executable='/bin/bash -i', as it thinks the whole value is the name of an executable. So if your alias is defined in the user's normal interactive startup, e.g. in .bashrc, then you'll have to invoke the command using this alternative form:

      subprocess.call(['/bin/bash', '-i', '-c', command])
      # i.e. shell=False (the default)