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. By using if-else statements with sys.platform, it is similar to the #ifdef compiler flag in the C/C++ universe. 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!")

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)

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. If you have questions about an embedded project you’re working on, Dojo Five can help you with all aspects of your devops for embedded journey! We are always happy to hear about cool projects or interesting problems to solve, so don’t hesitate to reach out and chat with us on LinkedIn or through email!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.