import streamlit as st from streamlitoptionmenu import optionmenu import os from dotenv…
- User
import streamlit as st
from streamlit_option_menu import option_menu import os from dotenv import load_dotenv load_dotenv()
import home, trending, account, your, about, buy_me_a_coffee st.set_page_config( page_title="Pondering", )
st.markdown( """ <script async src=f"https://www.googletagmanager.com/gtag/js?id={os.getenv('analytics_tag')}"> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', os.getenv('analytics_tag')); """, unsafe_allow_html=True) print(os.getenv('analytics_tag'))
class MultiApp:
def __init__(self): self.apps = [] def add_app(self, title, func): self.apps.append({ "title": title, "function": func }) def run(): # app = st.sidebar( with st.sidebar: app = option_menu( menu_title='Pondering ', options=['Home','Account','Trending','Your Posts','about','Buy_me_a_coffee'], icons=['house-fill','person-circle','trophy-fill','chat-fill','info-circle-fill'], menu_icon='chat-text-fill', default_index=1, styles={ "container": {"padding": "5!important","background-color":'black'}, "icon": {"color": "white", "font-size": "23px"}, "nav-link": {"color":"white","font-size": "20px", "text-align": "left", "margin":"0px", "--hover-color": "blue"}, "nav-link-selected": {"background-color": "#02ab21"},} ) if app == "Home": home.app() if app == "Account": account.app() if app == "Trending": trending.app() if app == 'Your Posts': your.app() if app == 'about': about.app() if app=='Buy_me_a_coffee': buy_me_a_coffee.app() run() like this i wanted the sidebar of my code import pandas as pdfrom docx import Document from docx.shared import Pt from docx.enum.text import WD_PARAGRAPH_ALIGNMENT import os import streamlit as st
Paths to the Word templates and additional DOCX files
TEMPLATE_PATH_NO = r"C:\Users\Administrator\Desktop\Chambers.docx" # Template for No rows TEMPLATE_PATH_YES = r"C:\Users\Administrator\Desktop\Chambers - Copy.docx" # Template for Yes rows AFTER_DOCX_PATH = r"C:\Users\Administrator\Desktop\new\After.docx"
Function to append Word documents
def append_docs(doc_list, output_doc): combined_doc = Document() for doc in doc_list: sub_doc = Document(doc) for element in sub_doc.element.body: combined_doc.element.body.append(element) combined_doc.save(output_doc)
def create_individual_document(template_path, data, matter_count, output_path): """Create an individual document for a row of data based on a template.""" doc = Document(template_path)
identifier_text = f"Matter {matter_count}" # Update table content dynamically doc.tables[0].cell(1, 0).text = identifier_text cell = doc.tables[0].cell(1, 0) # Formatting for paragraph in cell.paragraphs: for run in paragraph.runs: run.font.name = 'Times New Roman' run.font.size = Pt(12) run.font.bold = True cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER # Populate the document with data doc.tables[0].cell(2, 0).text = f" {data['Client Name '].strip()}" doc.tables[0].cell(3, 0).text = f" {data['Description (in 500 words)'].strip()}" doc.tables[0].cell(4, 0).text = f" {data['Value '].strip()}" doc.tables[0].cell(6, 0).text = f" {data['Lead partners'].strip()}" doc.tables[0].cell(7, 0).text = f" {data['Team Members'].strip()}" doc.tables[0].cell(8, 0).text = f" {data['Other Firms/counsels Involved'].strip()}" doc.tables[0].cell(9, 0).text = f" {data['Current Status (ongoing / completed )'].strip()}" # Save the document doc.save(output_path) return output_pathdef populate_chambers(excel_file, output_path): """Generate documents based on the Excel input.""" try: df = pd.read_excel(excel_file) individual_docs_no = [] individual_docs_yes = []
df_no = df[df['Confidential / Publishable '].str.strip().str.lower() == 'no'] df_yes = df[df['Confidential / Publishable '].str.strip().str.lower() == 'yes'] for index, row in df_no.iterrows(): temp_output_path = f"temp_publishable_no_{index}.docx" individual_docs_no.append(create_individual_document(TEMPLATE_PATH_NO, row, index + 1, temp_output_path)) for index, row in df_yes.iterrows(): temp_output_path = f"temp_publishable_yes_{index}.docx" individual_docs_yes.append(create_individual_document(TEMPLATE_PATH_YES, row, index + 1, temp_output_path)) append_docs(individual_docs_no + [AFTER_DOCX_PATH] + individual_docs_yes, output_path) for doc_path in individual_docs_no + individual_docs_yes: os.remove(doc_path) except Exception as e: st.error(f"Error occurred: {e}")Placeholder for Legal Era functionality
def populate_legal_era(excel_file): st.warning("Legal Era functionality is not implemented yet.")
Streamlit App
def main(): st.set_page_config(page_title="Document Automation", layout="wide")
st.markdown( """ <style> /* Sidebar styling */ [data-testid="stSidebar"] { background-color: #fdfcfc"; width: 70px !important; # Set the width to your desired value padding-top: 20px; } /* Sidebar title */ [data-testid="stSidebar"] h1 { font-size: 22px !important; color: black; text-align: center; } /* Sidebar radio buttons */ .stRadio > label { font-size: 18px !important; color: #5d3aa0; font-weight: bold; padding: 10px 5px; display: block; text-align: left; } .stRadio div[role="radiogroup"] label { font-size: 16px !important; margin-bottom: 10px; padding: 8px; border-radius: 5px; transition: background-color 0.3s ease-in-out; } /* Hover effect */ .stRadio div[role="radiogroup"] label:hover { background-color: #e0e0e0; } </style> """, unsafe_allow_html=True, ) st.markdown( """ <style> section[data-testid="stSidebar"] { width: 50px !important; # Set the width to your desired value } </style> """, unsafe_allow_html=True,)
st.sidebar.title("S&A SUBMISSIONS") pages = { "Home": "home", "ALB Asia IP Rankings": "alb", "Chambers": "chambers", "Legal Era": "legal_era", "IFLR 1000": "iflr", "Legal 500": "legal_500" } selected_option = st.sidebar.radio("", list(pages.keys())) if selected_option == "Home": st.header("Welcome to the Document Automation Tool!") st.markdown(""" This tool automates legal document generation for various submissions. Currently, forms are under testing, and this is a trial version. """) st.markdown("Only the BLUEPRINT we will make the changes as per the discussion") elif selected_option == "Chambers": st.header("Chambers Submission") st.markdown("🔧 **This implementation is still in progress. The production version is not yet live.** For testing, use this link: [Click Here](http://localhost:8501/)", unsafe_allow_html=True) excel_file = st.file_uploader("Upload Excel File for Chambers", type=["xlsx", "xls"]) if st.button("Generate Chambers Form"): if excel_file: output_path = "Chambers_Submission.docx" populate_chambers(excel_file, output_path) if os.path.exists(output_path): st.success("Chambers Form generated successfully!") with open(output_path, "rb") as f: st.download_button( label="Download Form", data=f, file_name="Chambers.docx", mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document" ) else: st.error("Error generating document.") else: st.error("Please upload an Excel file.") elif selected_option == "Legal Era": st.header("Legal Era Submission") excel_file = st.file_uploader("Upload Excel File for Legal Era", type=["xlsx", "xls"]) if st.button("Generate Legal Era Form"): if excel_file: populate_legal_era(excel_file) st.success("Processing completed (Placeholder).") else: st.error("Please upload an Excel file.") elif selected_option == "IFLR 1000": st.header("IFLR 1000 Submission") excel_file = st.file_uploader("Upload Excel File for IFLR 1000", type=["xlsx", "xls"]) if st.button("Generate IFLR 1000 Form"): if excel_file: st.success("Processing completed (Placeholder).") else: st.error("Please upload an Excel file.") elif selected_option == "IFLR 1000": st.header("IFLR 1000 Submission") excel_file = st.file_uploader("Upload Excel File for IFLR 1000", type=["xlsx", "xls"]) if st.button("Generate IFLR 1000 Form"): if excel_file: st.success("Processing completed (Placeholder).") else: st.error("Please upload an Excel file.") elif selected_option == "ALB Asia IP Rankings": st.header("Under Development") # excel_file = st.file_uploader("Upload Excel File for IFLR 1000", type=["xlsx", "xls"]) # if st.button("Generate IFLR 1000 Form"): # if excel_file: # st.success("Processing completed (Placeholder).") # else: # st.error("Please upload an Excel file.") # elif selected_option == "Legal 500": st.header("Under Development")if name == "main": main() in this remove th chmbers populatr code for the chmbers page from this....make it like above so that in chmbers and other foms i can write their fucnotnality when we clcik them
- Assistant
To refactor your Streamlit application in a way that encapsulates the functionalities for different sections (like "Chambers" and others) similarly to your multi-app structure in the first section of code, you can create a
MultiAppstructure for each of the functionalities (like Chambers, Legal Era, etc.). This way, when an option in the sidebar is selected, the appropriate functionality can be displayed without cluttering the main section of your code.Here’s how you could modify the existing code to achieve this by creating separate modules for each functionality and integrating them into the main Streamlit app.
Step 1: Organize Your App into Modules
First, ensure you have separate Python files for each functionality (for example,
chambers.py,legal_era.py,iflr_1000.py, etc.). Here’s a simple outline for how achambers.pyfile might look:# chambers.py import streamlit as st def app(): st.header("Chambers Submission") st.markdown("🔧 **This implementation is still in progress. The production version is not yet live.**") excel_file = st.file_uploader("Upload Excel File for Chambers", type=["xlsx", "xls"]) if st.button("Generate Chambers Form"): if excel_file: output_path = "Chambers_Submission.docx" # Call your populate_chambers function here # populate_chambers(excel_file, output_path) # Download functionality if os.path.exists(output_path): st.success("Chambers Form generated successfully!") with open(output_path, "rb") as f: st.download_button( label="Download Form", data=f, file_name="Chambers.docx", mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document" ) else: st.error("Error generating document.") else: st.error("Please upload an Excel file.")Step 2: Refactor the Main App File
Then, you would use
MultiAppin your main file to load the modules dynamically. Here is how you could refactor your main Streamlit app:import streamlit as st from streamlit_option_menu import option_menu import os from dotenv import load_dotenv from multiapp import MultiApp import chambers # Make sure to create this module import legal_era # Add other modules similarly load_dotenv() st.set_page_config(page_title="Document Automation") class MultiApp: def __init__(self): self.apps = [] def add_app(self, title, func): self.apps.append({ "title": title, "function": func }) def run(self): with st.sidebar: app = option_menu( menu_title='Pondering', options=['Home', 'Chambers', 'Legal Era', 'IFLR 1000'], icons=['house-fill', 'trophy-fill', 'info-circle-fill'], menu_icon='chat-text-fill', default_index=0 ) for app_dict in self.apps: if app == app_dict['title']: app_dict['function']() @app = MultiApp() @app.add_app("Home", home.app) # if you have a home module as well @app.add_app("Chambers", chambers.app) @app.add_app("Legal Era", legal_era.app) @app.add_app("IFLR 1000", iflr_1000.app) # Create and import this module similarly app.run()Conclusion
This restructuring not only keeps your code modular but also makes managing different functionalities easier. Each section (Chambers, Legal Era, etc.) can evolve independently without cluttering the core app layout. Make sure to create the respective functionality for each of those sections (like Legal Era, IFLR 1000, etc.) similarly to how you did for Chambers.
- User
add the css designig of the above pondering sidebar
- Assistant
To incorporate the CSS styling for the sidebar from your original "Pondering" app into the refactored Streamlit application, you can include the CSS styles before you render the sidebar. Below, I've added the appropriate CSS styling into the main app code. This styling will enhance the appearance of the sidebar, maintaining the design you initially had.
Below is the complete code with the CSS for the sidebar included:
Step 1: Refactored Main App with CSS
import streamlit as st from streamlit_option_menu import option_menu import os from dotenv import load_dotenv from multiapp import MultiApp import chambers # Make sure to create this module import legal_era # Add other modules similarly load_dotenv() st.set_page_config(page_title="Document Automation") # CSS styling for the sidebar st.markdown( """ <style> /* Global styling */ body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #fdfcfc; } /* Sidebar styling */ [data-testid="stSidebar"] { background-color: black; padding-top: 20px; } /* Sidebar title */ [data-testid="stSidebar"] h1 { font-size: 22px !important; color: white; text-align: center; } /* Sidebar option styling */ .stSidebar > div { color: white !important; } /* Sidebar radio buttons */ .stRadio > label { font-size: 18px !important; color: #5d3aa0; font-weight: bold; padding: 10px 5px; display: block; text-align: left; } .stRadio div[role="radiogroup"] label { font-size: 16px !important; margin-bottom: 10px; padding: 8px; border-radius: 5px; transition: background-color 0.3s ease-in-out; } /* Hover effect */ .stRadio div[role="radiogroup"] label:hover { background-color: #e0e0e0; } /* Selected option styling */ .stRadio div[role="radiogroup"] label[aria-checked="true"] { background-color: #02ab21; color: white; } </style> """, unsafe_allow_html=True, ) class MultiApp: def __init__(self): self.apps = [] def add_app(self, title, func): self.apps.append({ "title": title, "function": func }) def run(self): with st.sidebar: app = option_menu( menu_title='Pondering', options=['Home', 'Chambers', 'Legal Era', 'IFLR 1000'], icons=['house-fill', 'trophy-fill', 'info-circle-fill'], menu_icon='chat-text-fill', default_index=0, styles={'container': {'padding': '5!important', 'background-color': 'black'}, 'icon': {'color': 'white', 'font-size': '23px'}, 'nav-link': {'color': 'white', 'font-size': '20px', 'text-align': 'left', 'margin': '0px', '--hover-color': 'blue'}, 'nav-link-selected': {'background-color': '#02ab21'},} ) for app_dict in self.apps: if app == app_dict['title']: app_dict['function']() app = MultiApp() @app.add_app("Home", home.app) # assuming you have created a home module @app.add_app("Chambers", chambers.app) @app.add_app("Legal Era", legal_era.app) @app.add_app("IFLR 1000", iflr_1000.app) # Create and import this module similarly app.run()Step 2: Modify Chamber Module (As Example)
Here’s a quick reminder to ensure that your
chambers.pymodule looks like this, just for context:# chambers.py import streamlit as st def app(): st.header("Chambers Submission") st.markdown("🔧 **This implementation is still in progress. The production version is not yet live.**") excel_file = st.file_uploader("Upload Excel File for Chambers", type=["xlsx", "xls"]) if st.button("Generate Chambers Form"): if excel_file: output_path = "Chambers_Submission.docx" # Call your populate_chambers function here # populate_chambers(excel_file, output_path) # Download functionality if os.path.exists(output_path): st.success("Chambers Form generated successfully!") with open(output_path, "rb") as f: st.download_button( label="Download Form", data=f, file_name="Chambers.docx", mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document" ) else: st.error("Error generating document.") else: st.error("Please upload an Excel file.")Summary
By organizing your code this way, you maintain modularity and readability, while still being able to apply the desired CSS styling to your sidebar. Each functionality can also be easily expanded upon in their respective modules without cluttering the main application logic.
- User
what to install
- Assistant
To run the Streamlit application with the structure and functionality provided above, you'll need to ensure that you have the following packages installed in your Python environment. Below is a list of packages you’ll need along with installation commands.
Required Packages
- Streamlit: The main framework for building the web application.
- Streamlit Option Menu: A library to create a stylish sidebar menu.
- Pandas: For data manipulation and processing, especially for reading Excel files.
- python-docx: This library allows you to create and modify Word (.docx) files.
- python-dotenv: To manage environment variables in your application.
Installation Commands
You can install these packages using
pip. Open your command prompt or terminal and run the following commands:pip install streamlit pip install streamlit-option-menu pip install pandas pip install python-docx pip install python-dotenvAdditional Information
-
Python Version: Make sure you have Python 3.7 or later installed as Streamlit may have compatibility issues with older versions.
-
Virtual Environment (Optional): It’s often a good practice to create a virtual environment for your projects to manage dependencies. You can set it up with the following commands:
python -m venv myenv # Create a virtual environment named 'myenv' cd myenv # Navigate into the virtual environment source Scripts/activate # Activate the virtual environment (Windows) # OR source bin/activate # Activate the virtual environment (macOS/Linux) -
Starting the Streamlit App: Once you've installed the necessary packages and created the modules for the application, you can run your Streamlit app using:
streamlit run your_main_file.pyReplace
your_main_file.pywith the name of your main Python file that contains theMultiAppstructure (for example,app.py).
By following these steps, you should have everything you need to set up and run your Streamlit application! If you encounter any errors during installation or while running the application, feel free to ask for further assistance.
- User
File "C:\Users\Administrator\Desktop\dev\pondering\main.py", line 36 @app = MultiApp() ^ SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='? import streamlit as st from streamlit_option_menu import option_menu import os from dotenv import load_dotenv from multiapp import MultiApp import chambers # Make sure to create this module import legal_era # Add other modules similarly
load_dotenv()
st.set_page_config(page_title="Document Automation")
class MultiApp: def init(self): self.apps = []
def add_app(self, title, func): self.apps.append({ "title": title, "function": func }) def run(self): with st.sidebar: app = option_menu( menu_title='Pondering', options=['Home', 'Chambers', 'Legal Era', 'IFLR 1000'], icons=['house-fill', 'trophy-fill', 'info-circle-fill'], menu_icon='chat-text-fill', default_index=0 ) for app_dict in self.apps: if app == app_dict['title']: app_dict['function']()@app = MultiApp()
@app.add_app("Home", home.app) # if you have a home module as well @app.add_app("Chambers", chambers.app) @app.add_app("Legal Era", legal_era.app) @app.add_app("IFLR 1000", iflr_1000.app) # Create and import this module similarly
app.run()
- Assistant
The error message you received indicates a syntax error in your code. The specific line reported:
@app = MultiApp()Here, the issue arises because you mistakenly used the
@symbol before the variable assignment. The@symbol is typically used for decorators in Python, not for variable assignments.Correct Syntax
You should remove the
@symbol from the line. It should simply be:app = MultiApp()Complete Corrected Code
Here's your updated and corrected code snippet:
import streamlit as st from streamlit_option_menu import option_menu import os from dotenv import load_dotenv from multiapp import MultiApp import chambers # Make sure to create this module import legal_era # Add other modules similarly load_dotenv() st.set_page_config(page_title="Document Automation") class MultiApp: def __init__(self): self.apps = [] def add_app(self, title, func): self.apps.append({ "title": title, "function": func }) def run(self): with st.sidebar: app = option_menu( menu_title='Pondering', options=['Home', 'Chambers', 'Legal Era', 'IFLR 1000'], icons=['house-fill', 'trophy-fill', 'info-circle-fill'], menu_icon='chat-text-fill', default_index=0 ) for app_dict in self.apps: if app == app_dict['title']: app_dict['function']() # Correcting the syntax error here by removing '@' app = MultiApp() @app.add_app("Home", home.app) # Assuming you have a home module app.add_app("Chambers", chambers.app) app.add_app("Legal Era", legal_era.app) app.add_app("IFLR 1000", iflr_1000.app) # Make sure to import this module similarly # Run the application app.run()Additional Notes
-
Ensure Your Modules Are Available: Make sure that you have created the
home,chambers,legal_era, andiflr_1000modules correctly, and that they contain the necessary functions (app()in this case). -
Indentation: Keep an eye on consistent indentation, especially in Python where it is critical.
-
Check Import Paths: Make sure that the import statement paths are correct and that the modules are in the same directory or properly referenced relatively.
-
Running the App: You can run the Streamlit application using the command:
streamlit run main.py
Replacing
main.pywith the actual name of your main file if it's different.After making these corrections, your code should run without the syntax error you encountered. If you face any more issues, feel free to ask!
-
- User
File "C:\Users\Administrator\Desktop\dev\pondering\main.py", line 43 app.run() ^ SyntaxError: invalid syntax
- Assistant
The
SyntaxErrorindicating an issue with theapp.run()line can occur if there is an unbalanced or incorrect indentation, or there might be an invalid character before that line. However, since you’ve already provided the surrounding context, let's troubleshoot with a clean examination of the code structure.Review the Complete Code
Here’s a complete example ensuring that all structural and indentation issues are addressed, along with placing the
app.run()call at the correct indentation level:import streamlit as st from streamlit_option_menu import option_menu import os from dotenv import load_dotenv from multiapp import MultiApp import chambers # Ensure this module exists with the correct function import legal_era # Ensure this module exists with the correct function import iflr_1000 # Ensure this module exists with the correct function import home # Ensure this module exists with the correct function load_dotenv() st.set_page_config(page_title="Document Automation") class MultiApp: def __init__(self): self.apps = [] def add_app(self, title, func): self.apps.append({ "title": title, "function": func }) def run(self): with st.sidebar: app_selection = option_menu( menu_title='Pondering', options=['Home', 'Chambers', 'Legal Era', 'IFLR 1000'], icons=['house-fill', 'trophy-fill', 'info-circle-fill'], menu_icon='chat-text-fill', default_index=0 ) # Run the selected app for app_dict in self.apps: if app_selection == app_dict['title']: app_dict['function']() # Create an instance of MultiApp app = MultiApp() # Add apps to the MultiApp instance app.add_app("Home", home.app) # Assuming you have a home module app.add_app("Chambers", chambers.app) app.add_app("Legal Era", legal_era.app) app.add_app("IFLR 1000", iflr_1000.app) # Make sure to import this module correctly # Run the application if __name__ == "__main__": app.run()Important Points
-
Indentation: Ensure that the indentation is consistent throughout your code. Python relies on indentation for defining blocks of code.
-
Correct Module Imports: Make sure that all the modules (
chambers,legal_era,iflr_1000,home) exist and are in the same directory as your main file or that the import paths are correct. -
Environment Protection: Place the
app.run()line inside theif __name__ == "__main__":block. This is a common practice in Python to ensure that certain code only runs when the script is executed directly rather than imported as a module in another script. -
Check for Hidden Characters: Sometimes, copying and pasting code from external sources can introduce hidden characters. You can try rewriting the offending line in your IDE or text editor to remove any hidden formatting.
Running the App
To run your app correctly, make sure you are in the same directory as your
main.pyfile, and execute:streamlit run main.pyThis should start your Streamlit app if everything is correctly set up. If you still encounter issues, please share the exact code snippet of the relevant section to provide specific advice.
-
- User
SyntaxError: File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\multiapp.py", line 90 print self.gen_usage(cmdname, command.usage) ^ SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)?
- Assistant
The error message you’re encountering indicates that there is a Python 2-style
printstatement being used in a file calledmultiapp.py. This suggests that themultiapp.pyfile you are using is written for Python 2, which does not require parentheses forprint, while you are running your code in Python 3, which does require parentheses for theprintfunction.Steps to Fix the Issue:
-
Update the
multiapp.pyfile: You can either edit the existingmultiapp.pyfile to change the print statements to be compatible with Python 3 or obtain an updated version ofmultiapp.pythat is intended for Python 3. -
Correcting Print Statements: If you want to modify it manually, locate the print statements and replace them with the appropriate Python 3 syntax by adding parentheses. For example:
# Change this: print self.gen_usage(cmdname, command.usage) # To this: print(self.gen_usage(cmdname, command.usage)) -
Using the Correct Version of
multiapp.py: A version ofmultiapp.py(the one that you were trying to create aMultiAppstructure) that is compatible with Python 3 should look something like this:Here’s an example of a basic
multiapp.pythat you can use:# multiapp.py import streamlit as st class MultiApp: def __init__(self): self.apps = [] def add_app(self, title, func): self.apps.append({"title": title, "function": func}) def run(self): app = st.sidebar.radio( "Select an app", self.apps, format_func=lambda app: app["title"] ) app["function"]() # Run the selected app function -
Reinstalling the Library: If you obtained the
multiapp.pyfrom an external library, consider reinstalling or updating that library. You may want to find an alternative package or repository that is maintained for Python 3.
Conclusion
After you make these changes, try running your application again. If you continue to encounter issues or if you are still looking for your version of the
multiapp.py, let me know, and I can help you with further instructions or code samples. -
- User
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)?
#!/usr/bin/env python """ MultiAppMultiApp is a command line tool for allowing single commands to run multiple functions (like
svnandtrac-admin).You'll need to do these:
-
Create a subclass of
MultiApp. Give it the attributesname(a short, friendly name for the app),version(as a string, the version number of the app), andshortdesc(50 chars or less, a short description). If the subclass has a docstring, it is printed when the main help is called - it should not be very long, or incorporate description of the subcommands - they are included at the bottom by default. -
For each command you want to run, define a method named
do_commandname. It should accept positional arguments. You can give them names, and as an added bonus, if a TypeError is caught, the usage message will be displayed if it is set. -
This command should have a docstring to be accessed by the built-in
helpcommand. -
Give the command usage and description values. Do this with::
do_foo.descr = "A command that will foo." do_foo.usage = "[OPTIONS...] BAR"
Other things of note:
- You can add non-command help files by creating a
topicsdictionary as an attribute of the class. - If you remap the built-in
helpcommand, set the class'shelp_cmdattribute so the application can print a properFor help, type...message. - If you need to access one of the commands, use
self.getcmd, because it will automatically prefix the "do_" and display a patronizing error message if the command doesn't exist. - Command names can have dashes in them, but the actual methods must have underscores where the dashes are typed. They can still have underscores, and they won't be converted. """
import sys import os from os.path import basename from iotk import *
class MultiApp: """ This is a base class for MultiApp. You can populate it with commands by creating, documenting, and providing certain attributes to methods of a subclass of MultiApp. """ name = "<>" version = "2008.12.2" shortdesc = "This is the base class for command-line apps"
topics = dict() commands = dict() help_cmd = "help" def cmd_list(self): """ This will hunt down every command, even those in base classes. Code lovingly ripped off from ``cmd.Cmd`` in the Standard Library. """ names = [] classes = [self.__class__] while classes: aclass = classes.pop(0) if aclass.__bases__: classes = classes + list(aclass.__bases__) names = names + dir(aclass) return [attrib for attrib in names if attrib.startswith("do_")] def run(self, args=sys.argv): self.ename = basename(args[0]) if len(args) < 2: self.default() return cmdname = args[1] if len(args) > 2: arguments = args[2:] else: arguments = [] if self.cmd_to_fn(cmdname) in self.cmd_list(): command = self.getcmd(cmdname) try: command(*arguments) except TypeError: if hasattr(command, "usage"): print(self.gen_usage(cmdname, command.usage)) else: print "Wrong parameters supplied." print "Type '" + self.gen_help() + "' for help topics" else: self.notfound(cmdname) def gen_usage(self, name, usage): return "USAGE: " + self.ename + " " + name + " " + usage def cmd_to_fn(self, name): return "do_" + name.replace("-", "_") def fn_to_cmd(self, name): return name[3:].replace("_", "-") def gen_help(self): return self.ename + " " + self.help_cmd def notfound(self, cmdname): print "Command", cmdname, "does not exist." print "Type '" + self.gen_help() + "' for help topics'" def default(self): header = self.name + " " + self.version print_header(header) print self.shortdesc print print "USAGE: " + self.ename + " [subcommand] [arguments]" print "Type '" + self.gen_help() + "' for help topics" def do_help(self, *args): """ This is the online help system. It displays information about commands and assorted other help topics defined by the application. Simply typing "help" will list all help topics, while typing "help something" will display the full command. """ if not args: self.help_index() else: self.help_topic(args[0]) do_help.usage = "[COMMAND-OR-TOPIC]" do_help.descr = "Get info on commands and other functions." def gen_descrs(self): descrs = dict() for comname in self.cmd_list(): command = getattr(self, comname) if hasattr(command, "descr"): descrs[self.fn_to_cmd(comname)] = command.descr else: descrs[self.fn_to_cmd(comname)] = "---" return descrs def help_index(self): print_header(self.name + " Help Topics") if self.__doc__: print trim_docstring(self.__doc__) print if self.topics: print_header("Topics", underline="-", just="left") print_list(self.topics.keys(), sort=True) print if self.cmd_list(): print_header("Commands", underline="-", just="left") print_dict(self.gen_descrs(), space=2, sort=True) print def help_topic(self, lookup): if self.cmd_to_fn(lookup) in self.cmd_list(): self.cmd_help(lookup) elif lookup in self.topics: self.topic_help(lookup) else: print "There's not a help topic named that." print "Type '" + self.gen_help() + "' for help topics" return def cmd_help(self, cmdname): command = self.getcmd(cmdname) print print_header(self.name + ": Help for command '" + cmdname + "'") if hasattr(command, "usage"): print self.gen_usage(cmdname, command.usage) if command.__doc__: print print trim_docstring(command.__doc__) else: if hasattr(command, "descr"): print print command.descr else: print print "Sorry, no help for this command." print def topic_help(self, lookup): print print_header(self.name + ": Help on topic '" + lookup + "'") print self.topics[lookup] print def getcmd(self, something): cmdname = self.cmd_to_fn(something) if hasattr(self, cmdname): return getattr(self, cmdname) else: print "Horrible Error: Command", cmdname, "not found."if name == "main": class TestApp(MultiApp): """ This is just a simple test application. You can use this to get an idea of how to use MultiApp. """ name = "MultiApp Test" version = "0.0" shortdesc = "This is an app designed to test out MultiApp."
topics = {'dummy-topic': "This is just a dummy help topic. Disregard it."} def do_alpha(self, *args): """ Prints the arguments passed to it. Note that this does not include the program's name and ``alpha`` itself, just everything after that. """ print "Arguments: " for arg in args: print arg do_alpha.usage = "[ARGUMENTS...]" do_alpha.descr = "Lists all of the arguments passed to it." def do_bravo(self, name): """ Says "Hello, NAME!" Intended to test out argument-error-catching facilities. """ print "Hello, " + name + "!" do_bravo.usage = "NAME" do_bravo.descr = "Says Hello, NAME!" def do_charlie_delta(self, *args): """ Prints the arguments passed to it. It's just like ``alpha``, but it has a hyphen to test out the concept of hyphenated commands. """ print "Arguments: " for arg in args: print arg do_charlie_delta.usage = "[ARGUMENTS...]" do_charlie_delta.descr = "Does the same thing as alpha, but " \ "with a hyphen in the name and a longer description." def do_echo(self, *args): # Completely undocumented. print "Arguments: " for arg in args: print arg app = TestApp() app.run() -
- Assistant
The error you are encountering is due to syntax that is compatible with Python 2 but not with Python 3. In Python 3, the
printstatement has been replaced with theprint()function, requiring parentheses.Here's how to modify the
multiapp.pycode you provided to be compatible with Python 3:Updated Code for Python 3 Compatibility
You need to change every instance of
printto use parentheses. Below is the corrected version of your providedmultiapp.pyfile:#!/usr/bin/env python """ MultiApp ======== MultiApp is a command line tool for allowing single commands to run multiple functions (like ``svn`` and ``trac-admin``). You'll need to do these: 1. Create a subclass of ``MultiApp``. Give it the attributes ``name`` (a short, friendly name for the app), ``version`` (as a string, the version number of the app), and ``shortdesc`` (50 chars or less, a short description). If the subclass has a docstring, it is printed when the main help is called - it should not be very long, or incorporate description of the subcommands - they are included at the bottom by default. 2. For each command you want to run, define a method named ``do_commandname``. It should accept positional arguments. You can give them names, and as an added bonus, if a TypeError is caught, the usage message will be displayed if it is set. 3. This command should have a docstring to be accessed by the built-in ``help`` command. 4. Give the command usage and description values. Do this with:: do_foo.descr = "A command that will foo." do_foo.usage = "[OPTIONS...] BAR" Other things of note: - You can add non-command help files by creating a ``topics`` dictionary as an attribute of the class. - If you remap the built-in ``help`` command, set the class's ``help_cmd`` attribute so the application can print a proper ``For help, type...`` message. - If you need to access one of the commands, use ``self.getcmd``, because it will automatically prefix the "do_" and display a patronizing error message if the command doesn't exist. - Command names can have dashes in them, but the actual methods must have underscores where the dashes are typed. They can still have underscores, and they won't be converted. """ import sys import os from os.path import basename class MultiApp: """ This is a base class for MultiApp. You can populate it with commands by creating, documenting, and providing certain attributes to methods of a subclass of MultiApp. """ name = "<<MultiApp>>" version = "2008.12.2" shortdesc = "This is the base class for command-line apps" topics = dict() commands = dict() help_cmd = "help" def cmd_list(self): """ This will hunt down every command, even those in base classes. Code lovingly ripped off from ``cmd.Cmd`` in the Standard Library. """ names = [] classes = [self.__class__] while classes: aclass = classes.pop(0) if aclass.__bases__: classes = classes + list(aclass.__bases__) names = names + dir(aclass) return [attrib for attrib in names if attrib.startswith("do_")] def run(self, args=sys.argv): self.ename = basename(args[0]) if len(args) < 2: self.default() return cmdname = args[1] if len(args) > 2: arguments = args[2:] else: arguments = [] if self.cmd_to_fn(cmdname) in self.cmd_list(): command = self.getcmd(cmdname) try: command(*arguments) except TypeError: if hasattr(command, "usage"): print(self.gen_usage(cmdname, command.usage)) # Use print() function else: print("Wrong parameters supplied.") # Use print() function print("Type '" + self.gen_help() + "' for help topics") # Use print() function else: self.notfound(cmdname) def gen_usage(self, name, usage): return "USAGE: " + self.ename + " " + name + " " + usage def cmd_to_fn(self, name): return "do_" + name.replace("-", "_") def fn_to_cmd(self, name): return name[3:].replace("_", "-") def gen_help(self): return self.ename + " " + self.help_cmd def notfound(self, cmdname): print("Command", cmdname, "does not exist.") # Use print() function print("Type '" + self.gen_help() + "' for help topics") # Use print() function def default(self): header = self.name + " " + self.version print(header) # Use print() function print(self.shortdesc) # Use print() function print() print("USAGE: " + self.ename + " [subcommand] [arguments]") # Use print() function print("Type '" + self.gen_help() + "' for help topics") # Use print() function def do_help(self, *args): """ This is the online help system. It displays information about commands and assorted other help topics defined by the application. Simply typing "help" will list all help topics, while typing "help something" will display the full command. """ if not args: self.help_index() else: self.help_topic(args[0]) do_help.usage = "[COMMAND-OR-TOPIC]" do_help.descr = "Get info on commands and other functions." def gen_descrs(self): descrs = dict() for comname in self.cmd_list(): command = getattr(self, comname) if hasattr(command, "descr"): descrs[self.fn_to_cmd(comname)] = command.descr else: descrs[self.fn_to_cmd(comname)] = "---" return descrs def help_index(self): print(self.name + " Help Topics") # Use print() function if self.__doc__: print(self.__doc__.strip()) # Changed to use print() function print() if self.topics: print("Topics:") # Use print() function print(", ".join(self.topics.keys())) # Use print() function print() if self.cmd_list(): print("Commands:") # Use print() function for comname in self.gen_descrs(): print(f"- {comname}: {self.gen_descrs()[comname]}") # Use print() function print() def help_topic(self, lookup): if self.cmd_to_fn(lookup) in self.cmd_list(): self.cmd_help(lookup) elif lookup in self.topics: self.topic_help(lookup) else: print("There's not a help topic named that.") # Use print() function print("Type '" + self.gen_help() + "' for help topics") # Use print() function return def cmd_help(self, cmdname): command = self.getcmd(cmdname) print() print("Help for command '" + cmdname + "'") # Use print() function if hasattr(command, "usage"): print(self.gen_usage(cmdname, command.usage)) # Use print() function if command.__doc__: print() print(command.__doc__.strip()) # Use print() function else: if hasattr(command, "descr"): print() print(command.descr) # Use print() function else: print() print("Sorry, no help for this command.") # Use print() function print() def topic_help(self, lookup): print() print("Help on topic '" + lookup + "'") # Use print() function print(self.topics[lookup]) # Use print() function print() def getcmd(self, something): cmdname = self.cmd_to_fn(something) if hasattr(self, cmdname): return getattr(self, cmdname) else: print("Error: Command", cmdname, "not found.") # Use print() function if __name__ == "__main__": class TestApp(MultiApp): """ This is just a simple test application. You can use this to get an idea of how to use MultiApp. """ name = "MultiApp Test" version = "0.0" shortdesc = "This is an app designed to test out MultiApp." topics = {'dummy-topic': "This is just a dummy help topic. Disregard it."} def do_alpha(self, *args): """ Prints the arguments passed to it. Note that this does not include the program's name and ``alpha`` itself, just everything after that. """ print("Arguments: ") # Use print() function for arg in args: print(arg) # Use print() function do_alpha.usage = "[ARGUMENTS...]" do_alpha.descr = "Lists all of the arguments passed to it." def do_bravo(self, name): """ Says "Hello, NAME!" Intended to test out argument-error-catching facilities. """ print("Hello, " + name + "!") # Use print() function do_bravo.usage = "NAME" do_bravo.descr = "Says Hello, NAME!" def do_charlie_delta(self, *args): """ Prints the arguments passed to it. It's just like ``alpha``, but it has a hyphen to test out the concept of hyphenated commands. """ print("Arguments: ") # Use print() function for arg in args: print(arg) # Use print() function do_charlie_delta.usage = "[ARGUMENTS...]" do_charlie_delta.descr = "Does the same thing as alpha, but " \ "with a hyphen in the name and a longer description." def do_echo(self, *args): # Completely undocumented. print("Arguments: ") # Use print() function for arg in args: print(arg) # Use print() function app = TestApp() app.run()Key Changes
- Updated
printstatements: Eachprintstatement now uses parentheses to conform to Python 3 syntax. - Usage of
.strip(): Cleaned up any string output with.strip()where necessary to remove extra new lines.
Next Steps
- Replace the Existing MultiApp Code: Make sure to replace your existing
multiapp.pywith the updated code above. - Run Your Application: After updating the file, try running your Streamlit application again, and it should work without
SyntaxError. - Test Functionality: Make sure to also test the functionality to ensure that all commands and help topics behave as expected.
Feel free to reach out if you encounter any other issues or need further assistance!
- Updated