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

Laptop with some code on screen

I want to write my first embedded program. Where do I start?

The boom in the Internet of Things (IoT) commercial devices and hobbyist platforms like the Raspberry Pi and Arduino have created a lot of options, offering inexpensive platforms with easy to use development tools for creating embedded projects. You have a lot of options to choose from. An embedded development platform is typically a microcontroller chip mounted on a circuit board designed to show off its features. There are typically two types out there: there are inexpensive versions, sometimes called

Read More »
Medical device monitoring vitals

IEC-62304 Medical Device Software – Software Life Cycle Processes Primer – Part 1

IEC-62304 Software Lifecycle requires a lot of self-reflection to scrutinize and document your development processes. There is an endless pursuit of perfection when it comes to heavily regulated industries. How can you guarantee something will have zero defects? That’s a pretty hefty task. The regulatory approach for the medical device industry is process control. The concept essentially states that if you document how every step must be completed, and provide checks to show every step has been completed properly, you

Read More »
Operating room filled with medical devices

IEC-62304 Medical Device Software – Software Life Cycle Processes Primer – Part II

Part I provides some background to IEC-62304. Part II provides a slightly more in-depth look at some of the specifics. The IEC 62304 Medical Device Software – Software Lifecycle Processes looks into your development processes for creating and maintaining your software. The standard is available for purchase here. So what activities does the standard look at? Here are some of the major topics. For any given topic, there will be a lot more specifics. This will look at a few

Read More »