Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross platform code in python

Tags:

python

How can I write in python some windows code to execute only when I am running the script in widnows, if I should run it in linux, that part of the windows code should be ignored, something simillar to this, in C++:

#ifdef windows
  //code
#endif

#ifdef linux
//code
#endif

I tried something like this in python:

if os.name = 'nt':
   #code

But in linux it gives me an error(I am using STARTF_USESHOWWINDOW, witch gives error).

startupinfo = None
if sys.platform == 'win32':
    startupinfo = subprocess.STARTUPINFO()
    startupinfo.dwFlags |= _subprocess.STARTF_USESHOWWINDOW #error here
    startupinfo.wShowWindow = _subprocess.SW_HIDE # error here

Traceback (most recent call last):
  File "/home/astanciu/workspace/test/src/main.py", line 10, in <module>
    import _subprocess
ImportError: No module named _subprocess
like image 983
Adrian Avatar asked Jun 13 '26 08:06

Adrian


1 Answers

Checks for the platform should be necessary at much fewer places in Python than in C. If you really have to do it, the preferred way is to check sys.platform rather than os.name.

like image 116
Sven Marnach Avatar answered Jun 15 '26 22:06

Sven Marnach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!