Python in Posit Workbench

Users can write and execute Python code in all four IDEs available in Posit Workbench:

  1. VS Code
  2. JupyterLab
  3. Jupyter Notebook
  4. RStudio Pro

This section covers:

Python best practices

Default Python interpreter

Typically, your Workbench Server Administrator1 defines the default version of Python for the server. To identify your default version of Python, run the following command:

which python3

If you want to override this setting, use an alias that points to the Python interpreter you want to use as the default. For example, if you have Python 3.10.7 installed at /opt/python/3.10.7/bin/python3, you can use the following alias:

~/.bashrc
alias python="/opt/python/3.10.7/bin/python3"

Using multiple versions of Python

Workbench users can switch between multiple versions of Python. If your Server Administrator installed Python, you can identify all available versions of Python by running the following command:

$ ls -1d /opt/python/*
/opt/python/3.7.14
/opt/python/3.8.14
/opt/python/3.9.14
/opt/python/3.10.7

You can find additional information in the Installing Python section of the Posit Workbench Administrator Guide.

Next, users can choose their desired interpreter by directly invoking the absolute path to the interpreter (instead of invoking python3 only). For example:

$ /opt/python/3.10.7/bin/python3

Virtual environments

We recommend using virtual environments for all Python projects. Virtual environments create isolated Python environments, helping when projects have different dependency requirements. For example, you might have done some analysis last year using an older version of pandas. However, starting a new project today may require the latest version. Creating a virtual environment for each project ensures the old project continues using the old version of pandas and the new project uses the latest version.

To create and activate a virtual environment, run the following commands:

python3 -m venv .venv
source .venv/bin/activate

To create a virtual environment with a specific version of Python, invoke venv using the absolute path of the Python interpreter:

/opt/python/3.10.4/bin/python3 -m venv .venv
source .venv/bin/activate

Now, invoking the python3 command executes the Python interpreter in your virtual environment instead of the default interpreter:

which python3
# /usr/home/<username>/my-project/.venv/bin/python3

URL prefixes

When running in remote environments, many Python applications require users to specify the URL prefix of where the application is running. Setting this prefix varies by application, but you can use the rserver-url binary to generate the value for a given port. The rserver-url binary is located at /usr/lib/rstudio-server/bin, and we recommend adding this location to your $PATH for easy retrieval. Retrieving the prefix for a session running at https://workbench-server/s/4566a3c9ab5a7ad01e1a7/ for port 8050 would look like:

$ rserver-url -l 8050
https://workbench-server/s/4566a3c9ab5a7ad01e1a7/p/30507931/

This value changes with each session. Rather than hard-coding this value in your code, we recommend defining a variable that calls rserver-url each time you run your code. This code can be added to an if block that checks if the environment variable $RS_SERVER_URL has been set. This ensures that the code only executes rserver-url inside of Workbench and not when your code is running elsewhere. For example, the following code sets path to the value generated by rserver-url and passes it as the root_path variable to the Uvicorn ASGI server:

if __name__ == '__main__':
    path, port = '', 8050 
  
    # check if we're running in Posit Workbench
    if 'RS_SERVER_URL' in os.environ and os.environ['RS_SERVER_URL']:
        import subprocess
        # call rserver-url to retrieve path prefix 
        path = subprocess.run(f'echo $(rserver-url -l {port})',
                             stdout=subprocess.PIPE, shell=True).stdout.decode().strip()
    # pass prefix to ASGI server
    uvicorn.run(app, port = port, root_path = path)

Alternatively, rserver-url -l can be passed to your application by wrapping it in $() and passing it from the command line. For example, starting a Uvicorn server from the command line looks like the following:

$ uvicorn main:app --port=8050 --root-path=$(rserver-url -l 8050)

Additional Python resources

Many good resources are available online for learning Python and seeking answers to questions about various tasks. Explore the following resources for more information on learning and using Python.

Learning Python

The Python Software Foundation has developed many valuable resources for learning Python:

Asking questions

Creating an example often helps you think through your problem in a solvable way and helps others understand the issue clearly. For more on creating a reproducible example (reprex), see the How to create a Minimal, Reproducible Example page.

You may also want to check out the following resources:

  • The Posit Community is our discussion board for our community and it covers topics ranging across multiple programming languages and workflows.
  • Stack Overflow is an important resource for seeking answers to questions about Python - in particular, we’d recommend making sure your question is tagged as “python”.

News and information

Python developers form an active community, and many new developments occur regularly. If you want to stay updated on what’s happening, we recommend following these sites:

  • Follow the Posit blog to learn about our latest features, packages, and workshops.
  • Python-bloggers is a blog aggregator that reposts Python-related articles from across the web. Python-bloggers is a good place to find Python tutorials, announcements, and other random happenings.
  • The Python Software Foundation has several different newsgroups and mailing lists devoted to Python.

Other resources

  • The r/Python and r/learnpython subreddits are active communities with a wealth of knowledge that welcomes new members.
Back to top

Footnotes

  1. A Server Administrator is responsible for installing and maintaining the Workbench server(s). Typically, this person has SSH access to the server and root privileges. Often, the person in this role works in IT and is not a Workbench user.↩︎