Best Practice to Execute an EXE via os.popen() with White Spaces in the Path – Python Tutorial

By | August 15, 2019

In python, we can call windows exe application to run with os.popen(). In tutorial below, we can learn how to call a windows exe application to run.

Python Call .Exe File with Arguments – Python Tutorial

However, there is a problem we must fix. For example, if you call a cmd and there some white space in it. You will fail.


C:\Program Files\WinRAR\WinRAR.exe a Web Development.rar F:\Web Development.pdf -hp9d163 -m4 -ibck -ep

Because there are some white spaces in the cmd.

C:\Program Files\WinRAR\WinRAR.exe: one white space

Web Development.rar: one white space

Web Development.pdf: one white space

How to fix this problem?

You should use “” on white string.

Change the cmd above to:

"C:\Program Files\WinRAR\WinRAR.exe" a "F:\Web Development.rar" "F:\Web Development.pdf" -hp9d163 -m4 -ibck -ep

Here is an example code:

cmd = 'C:\\"Program Files"\\WinRAR\\WinRAR.exe a "' + dest_file + '" "' + src_file+'" -hp'+psw+" -m4 -ibck -ep"

Then you can use os.popen() to run this cmd successfully.