How to Prevent Your Python Script From Getting Culture Shock in Different OS’s

After hours of focusing, you finally finish writing a Python script for your project. It works perfectly on your computer and you pushed the changes to your favorite source control provider. The next thing you know, your teammate’s complaining that the script does not work on their computer because they are running on a different operating system. Does this ring a bell?

Here are a few tips for writing cross-platform python code so you never frustrate your teammate again!

Use sys.platform

sys.platform contains the name of the platform/operating system the Python script is running on in string. Using if-else statements with sys.platform in Python is similar to using the #ifdef compiler flag in C/C++. sys.platform returns ‘win32’ for the Windows machine, ‘linux’ for the Linux machine, and ‘darwin’ for the macOS machine. Click here for complete documentation of the sys module.

An example in the C/C++ universe:

#ifdef _WIN64
    ... // windows code goes here.
#elif __linux__
    ... // linux code goes here.
#elif __APPLE__
    ... // macOS code goes here.
#else 
#error "OS not supported!"
#endif

And the same code in the Python universe:

if (sys.platform == win32):
	# windows code goes here.
elif (sys.platform == linux):
	# linux code goes here.
elif (sys.platform == darwin):
	# macOS code goes here.
else:
	print("OS not supported!")
Book a Call with Dojo Five Embedded Experts

Use os.path.join

os.path.join intelligently concatenates one or more paths based on the operating system the Python script is running on. This module can be used independently without sys.platform. Click here for complete documentation of the os.path module.

A simple example:

folderName = "folder"
fileName = "file"

# The following lines of codes are not cross-platform because 
# this will work on Windows but fail on Linux/macOS machine and
path = "{}\\\\{}".format(folderName, fileName)

# this will work on Linux/macOS but fail on Windows machine.
path_1 = "{}/{}".format(folderName, fileName)

# The following line of code works for all platforms
path = os.path.join(folderName, fileName)

Other Considerations

Pathlib, a popular third party library, further simplifies pathnames on all platforms by creating a platform agnostic pathway for interacting with folder or file names on the disc. 

A simple example using pathlib:

import pathlib
folderName = "folder"
fileName = "file"

#cross platform code using pathlib

#create path object using folder and file
Path = pathlib.Path(folderName) / fileName

#print absolute path of the object
print(Path.resolve())

Outside of the world of files, there are also some considerations that should be made. It’s important to remember that some CMD line programs or utilities may be unavailable depending on the host system. For example, it may seem obvious that unix commands won’t be natively available on Windows, but remembering to make a habit of wrapping OS or subprocess calls to outside applications can save time debugging down the road. Finally, consider which common data encodings may be leveraged to reduce the possibility for misinterpreting data. For example UTF-8 is quite popular for representing text or ascii characters across all platforms. 

Summary

Even with the cross-platform code in place, the code should be tested on machines with the different OS before announcing it is officially done. Check out our Docker: An Ideal Development Environment blog post for more information. By doing so, the extra time used for revisiting the code can instead be used in developing features.

Dojo Five provides a number of services, including firmware development in Python, C, C++, embedded CI/CD, testing, and automation. We have talented engineers on hand ready to help you with all aspects of your EmbedOps journey. You can Book a Call with us to discuss your embedded project, or sign up for free for our EmbedOps CI and build management product.

Sign up to get our content updates!

Unlock the full potential of your embedded projects with our expert insights! Dive into our comprehensive resources to stay ahead in firmware development. Subscribe now to get the latest best practices and guides delivered straight to your inbox.

Sign Up for Updates

Discover why Dojo Five EmbedOps is the embedded enterprise choice for build tool and test management.

Sign up to receive a free account to the EmbedOps platform and start building with confidence..

  • Connect a repo
  • Use Dev Containers with your Continuous Integration (CI) provider
  • Analyze memory usage
  • Integrate and visualize static analysis results
  • Perform Hardware-in-the-Loop (HIL) tests
  • Install the Command Line Interface for a developer-friendly experience

Subscribe to our Monthly Newsletter

Subscribe to our monthly newsletter for development insights delivered straight to your inbox.

Interested in learning more?

Best-in-class embedded firmware content, resources and best practices

Futuristic data tube

Choosing an embedded development board

Choosing a first development board can be daunting with so many choices. Here are some examples to give you an idea of what you could consider for your first board. And as always, if you have a question – reach out to [email protected]. There is a community here to help you out. Lots of options in the development board arena This previous blog covered a number of factors to consider when choosing a first development board. Here are some examples

Read More »
Using Artifactory for Efficient Artifact Storage

Using Artifactory for Efficient Artifact Storage

Introduction Managing software artifacts efficiently is a critical challenge for software development teams. Whether you are dealing with versioning issues, dependency management, or maintaining previous builds for rollback and debugging, an inefficient artifact storage solution can slow down development cycles and introduce errors. Below is a list of questions to consider artifact management in your CI/CD processes: Are the number of binaries for your projects growing and struggling with tracking and retrieving different versions of your software builds, making debugging

Read More »
Addressing the CRA SBOM Mandate: How to Achieve Compliance

Addressing the CRA SBOM Mandate: How to Achieve Compliance

Written by: Joe Schneider The EU Cyber Resilience Act (CRA) has fundamentally changed embedded software development by mandating proof of a product’s secure operation and ability to remain safe throughout its lifecycle. Despite being an EU regulation, the CRA is applicable to any globally manufactured product targeting EU markets and has led many other jurisdictions to introduce similar cybersecurity initiatives. These include the USA’s Executive Order 14028, Japan’s METI’s Cybersecurity Management Guidelines and the UK’s Product Security and Telecommunications Infrastructure

Read More »