Skip to content Skip to sidebar Skip to footer

Call A Bash Function Within A Python Script

I have a python script (e.g. test.py) and a commands.txt file which contains a custom bash function (e.g. my_func) along with its parameters, e.g. my_func arg1 arv2; my_func arg3 a

Solution 1:

You will need to invoke bash directly, and instruct it to process both files.

At the command-line, this is:

bash -c '. ~/.bash_profile; . commands.txt'

Wrapping it in python:

subprocess.call(['bash', '-c', '. ~/.bash_profile; . commands.txt'])

You could also source ~/.bash_profile at the top of commands.txt. Then you'd be able to run a single file.

It may make sense to extract the function to a separate file, since .bash_profile is intended to be used by login shells, not like this.

Solution 2:

If the first line of your commands.txt file had the correct shebang (for example #!/bin/bash) making your file executable (chmod +x commands.txt) will be enough :

subprocess.call("path/to/commands.txt")

Post a Comment for "Call A Bash Function Within A Python Script"