Search code examples
pythonpyinstaller

Convert python script which runs a bash script to executable file with Pyinstaller


I want to convert a python script which runs a local bash script to executable file with Pyinstaller.

My project structure is as following:

Project/
|-- bash_script/
|   |-- script.sh
|-- main.py

The main.py contains a line which runs the script locally:

output = subprocess.check_output('./bash_script/script.sh', shell=True).decode()

Now, after converting the main.py to executable file in linux, if I run it on a different location from where main.py is located, it won't find the script.

I want to add the shell script to the python executable file, so it won't depend on the script locally, but, I will just have the executable file and it will eventually run.

I have tried using --add-data flag to pyinstaller converting commend, however it didn't work.

Thanks!


Note: I am using the following command:

pyinstaller --add-data "./bash_script/script.sh:." --onefile main.py

and I get an error after running in dist dir:

/bin/sh: 1: ./bash_script/script.sh: not found

Solution

  • In your main.py:

    import subprocess
    import os
    
    script = os.path.join(os.path.dirname(__file__),'bash_script','script.sh')
    output = subprocess.check_output(script, shell=True).decode()
    print(output)
    

    Then run:

    pyinstaller -F --add-data ./bash_script/script.sh:./bash_script main.py
    

    And bobs your uncle!

    p.s. -F is the same as --onefile