Cloud streamlit app and printing

Dear Guru,

I have employed this code successfully within VS Code and verified its functionality. However, when deploying it to the Streamlit cloud web app, it appears that the application is not running as expected.

Please give me advices!

import streamlit as st
from docxtpl import DocxTemplate
import subprocess
import os
import time
from datetime import datetime
import io

#---------Function to render Word document-------------
def render_docx(data):
    doc = DocxTemplate("template.docx")
    doc.render(data)
    return doc

#---------Function to print Word document----------------
def print_word_document(file_path):
    word_exe_path = r"C:\Program Files\Microsoft Office\Office16\winword.exe"
    process = subprocess.Popen([word_exe_path, file_path, "/mFilePrintDefault"])
    #process.wait()  # Wait for printing to finish
    time.sleep(5) # Wait for 5 seconds
    # Close the opened Word process after printing
    subprocess.call(["taskkill", "/F", "/IM", "WINWORD.EXE"])

    # Wait for the Word process to finish before deleting the file
    while os.path.exists(file_path):
        try:
            os.remove(file_path)
            break
        except PermissionError:
            time.sleep(0.5)

def main():
    st.title("Create and Print Word File")
    
    #----Create input section-------------------
    name = st.text_input("Enter your name:")

    #----Get current timestamp for the file name------
    current_time = datetime.now().strftime("%Y%m%d%H%M%S")

    #----If filename doesn't exist in session state, create a new one
    if not hasattr(st.session_state, "filename"):
        st.session_state.filename = f'{current_time}_{name}.docx'
    
    #----Button to create and download Word file -----------------
    if st.button("Create and Download Word File"):
        doc = render_docx({'name': name, 'timestamp': current_time})
        bio = io.BytesIO()
        doc.save(bio)
        
        st.download_button(
            label="Download Word File",
            data=bio.getvalue(),
            file_name=st.session_state.filename,
            mime='docx'
        )
        
        st.success(f"Successfully created and downloaded the Word file '{st.session_state.filename}'!")

    #----Button to print the created Word file--------------------------
    if st.button("Print Created Word File"):
        if hasattr(st.session_state, "filename"):

            #----Get information about the created file---------------------
            output_filename = st.session_state.filename
            st.write(output_filename)          
            output_path = os.path.join(r'C:\Users\phong.lh\Downloads', output_filename)
            st.write(output_path)

            print_word_document(output_path)
            st.success(f"Printed the Word file '{os.path.basename(output_path)}' and successfully closed the file!")

if __name__ == "__main__":
    main()


And this is my warning Trace-back:

[09:25:37] πŸ™ Pulling code changes from Github...

[09:25:39] πŸ“¦ Processing dependencies...

[09:25:39] πŸ“¦ Processed dependencies!

[09:25:40] πŸ”„ Updated app!

2023-08-18 09:27:35.606 Uncaught app exception

Traceback (most recent call last):

  File "/home/adminuser/venv/lib/python3.9/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 552, in _run_script

    exec(code, module.__dict__)

  File "/mount/src/streamlitdocx/pages/πŸ–¨_In_file_word.py", line 74, in <module>

    main()

  File "/mount/src/streamlitdocx/pages/πŸ–¨_In_file_word.py", line 70, in main

    print_word_document(output_path)

  File "/mount/src/streamlitdocx/pages/πŸ–¨_In_file_word.py", line 18, in print_word_document

    process = subprocess.Popen([word_exe_path, file_path, "/mFilePrintDefault"])

  File "/usr/local/lib/python3.9/subprocess.py", line 951, in __init__

    self._execute_child(args, executable, preexec_fn, close_fds,

  File "/usr/local/lib/python3.9/subprocess.py", line 1837, in _execute_child

    raise child_exception_type(errno_num, err_msg, err_filename)

FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Program Files\\Microsoft Office\\Office16\\winword.exe'

Hi,
You are trying to access the above exe file, however, it is not present on the Streamlit cloud server. This executable file must be added to your Github repo in order for you to use it, which I think is not possible in Github.
You can try and host your project on another server, with the exe file and all other dependencies include. However, I am pretty sure it will not work on the Streamlit community cloud server, though I may be wrong.

Cheers,
Moiz

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.