# Windows

## How to fix Python ModuleNotFoundError: No module named ‘cv2’ on Windows

### Problem:

You see an error message like the following one when running some Python code on Windows:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\ukoeh\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\cv_algorithms\__init__.py", line 5, in <module>
from .text import *
File "C:\Users\ukoeh\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\cv_algorithms\text.py", line 7, in <module>
import cv2
ModuleNotFoundError: No module named 'cv2'

### Solution:

Install the opencv-python package using

pip install opencv-python

and retry.

Posted by Uli Köhler in Python, Windows

## How to fix Visual Studio Code still not finding binary after changing PATH environment variable on Windows

### Problem:

Your Visual Studio Code integrated shell on Windows still doesn’t find a binary (e.g. a Python binary) even though you have just added it to the PATH environment variable and have opened a new shell in Visual Studio.

### Solution:

In order to reload the PATH environment variable, restart Visual Studio Code !

Posted by Uli Köhler in Windows

Run

$env:PATH to show the PATH environment variable in PowerShell. Posted by Uli Köhler in PowerShell, Windows ## How to fix Windows “echo$PATH” empty result

When you try to run

echo $PATH you will always get an empty result. Instead, if you are in cmd, use echo %PATH% but if you are using PowerShell, you need to use $env:PATH

Posted by Uli Köhler in PowerShell, Windows

## How to generate filename with date and time in PowerShell

You can use Get-Date like this to generate a date that is compatible with characters allowed in filenames:

Get-Date -UFormat "%Y-%m-%d_%H-%m-%S"

Example output:

2020-12-11_01-12-26

In order to generate a complete filename, surround that with $() and prepend/append other parts of your desired filename: mysqldump-$(Get-Date -UFormat "%Y-%m-%d_%H-%m-%S").sql

Posted by Uli Köhler in PowerShell, Windows

## How to make PowerShell output error messages in English

If you want to see a PowerShell output (e.g. an error message) in english instead of your local language, prefix your command by

[Threading.Thread]::CurrentThread.CurrentUICulture = 'en-US';

For example, in order to run to run My-Cmdlet -Arg 1 with output in English instead of your local language, use

[Threading.Thread]::CurrentThread.CurrentUICulture = 'en-US'; My-Cmdlet -Arg 1

[Threading.Thread]::CurrentThread.CurrentUICulture only affects the current command and does not have any effect for other commands. Hence your need to copy the command before each and every command for which you want to see the output in English.

Possibly you also need to install the English help files in order to see more messages in English. In order to do that, run this command in PowerShell as an administrator:

Update-Help -UICulture en-US

Posted by Uli Köhler in PowerShell, Windows

## How to find out if your WSL Ubuntu is running on WSL1 oder WSL2

In order to find out if your Ubuntu or other WSL linux installation is running on WSL1 or WSL2, open a Powershell and run

wsl --list -v

This will show you all WSL installations and the associated WSL versions:

PS C:\WINDOWS\system32> wsl --list -v
NAME      STATE           VERSION
* Ubuntu    Running         1

As you can see, the Ubuntu VM is running WSL VERSION 1.

Go to the WSL2 installation page for instructions on how to upgrade to WSL2.

Posted by Uli Köhler in Windows

## How to auto-set Windows audio balance to a specific L-R difference using Python

When you can’t place your speakers equally far from your ears, you need to adjust the audio balance in order to compensate for the perceived difference in volume.

Windows allows you to compensate the audio volume natively using the system settings – however it has one critical issue: If you ever set your audio volume to zero, your balance settings get lost and you need to click through plenty of dialogs in order to re-configure it.

In our previous post How to set Windows audio balance using Python we showed how tp use the pycaw library to  (see that post for installation instructions etc).

The following Python script can be run to set the audio balance to. It has been designed to keep the mean (i.e. L+R) audio level in dB when adjusting the volume (i.e. it will not change the overall volume and hence avoid blowing out your eardrums) and will not do any adjustment if the balance is already within 0.1 dB.

Set desiredDelta to your desired left-right difference in dB (positive values mean that the left speaker will be louder than the right speaker)!

from ctypes import cast, POINTER
from comtypes import CLSCTX_ALL
from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume
import math

# Get default audio device using PyCAW
devices = AudioUtilities.GetSpeakers()
interface = devices.Activate(
IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
volume = cast(interface, POINTER(IAudioEndpointVolume))

# Get current volume of the left channel
currentVolumeLeft = volume.GetChannelVolumeLevel(0)
# Set the volume of the right channel to half of the volume of the left channel
volumeL = volume.GetChannelVolumeLevel(0)
volumeR = volume.GetChannelVolumeLevel(1)
print(f"Before adjustment: L={volumeL:.2f} dB, R={volumeR:.2f} dB")

desiredDelta = 6.0 # Desired delta between L and R. Positive means L is louder!

delta = abs(volumeR - volumeL)
mean = (volumeL + volumeR) / 2.

# Re-configure balance if delta is not
if abs(delta - desiredDelta) > 0.1:
volume.SetChannelVolumeLevel(0, mean + desiredDelta/2., None) # Left
volume.SetChannelVolumeLevel(1, mean - desiredDelta/2., None) # Right
# Get & print new volume
volumeL = volume.GetChannelVolumeLevel(0)
volumeR = volume.GetChannelVolumeLevel(1)
print(f"After adjustment: L={volumeL:.2f} dB, R={volumeR:.2f} dB")
else:
print("No adjustment neccessary")

Posted by Uli Köhler in Audio, Python, Windows

## How to set Windows audio balance using Python

In our previous post we showed how to set the Windows audio volume using pycaw.

First, we install the library using

pip install pycaw

Note: pycaw does not work with WSL (Windows Subsystem for Linux)! You actually need to install it using a Python environment running on Windows. I recommend Anaconda.

In order to set the audio balance, we can use volume.SetChannelVolumeLevel(...):

from ctypes import cast, POINTER
from comtypes import CLSCTX_ALL
from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume
import math

# Get default audio device using PyCAW
devices = AudioUtilities.GetSpeakers()
interface = devices.Activate(
IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
volume = cast(interface, POINTER(IAudioEndpointVolume))

# Get current volume of the left channel
currentVolumeLeft = volume.GetChannelVolumeLevel(0)
# Set the volume of the right channel to half of the volume of the left channel
volume.SetChannelVolumeLevel(1, currentVolumeLeft - 6.0, None)
# NOTE: -6.0 dB = half volume !

Note that by convention, the left channel is channel 0 and the right channel is channel 1. Depending on the type of sound card, there might be as few as 1 channel (e.g. a mono headset) or many channels like in a multichannel USB audio interface. use volume.GetChannelCount() to get the number of channels.

Posted by Uli Köhler in Audio, Python, Windows

## How to set Windows audio volume using Python

We can use the pycaw library to set the Windows Audio volume using Python.

First, we install the library using

pip install pycaw

Note: pycaw does not work with WSL (Windows Subsystem for Linux)! You actually need to install it using a Python environment running on Windows. I recommend Anaconda.

Now we can set the volume to half the current volume using this script:

from ctypes import cast, POINTER
from comtypes import CLSCTX_ALL
from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume
import math

# Get default audio device using PyCAW
devices = AudioUtilities.GetSpeakers()
interface = devices.Activate(
IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
volume = cast(interface, POINTER(IAudioEndpointVolume))

# Get current volume
currentVolumeDb = volume.GetMasterVolumeLevel()
volume.SetMasterVolumeLevel(currentVolumeDb - 6.0, None)
# NOTE: -6.0 dB = half volume !

Posted by Uli Köhler in Audio, Python, Windows

## How to access COM1, COM2, … serial ports in Windows Subsystem for Linux (WSL)?

Accessing serial ports in WSL is really simple:

• COM1 is mapped to /dev/ttyS1
• COM2 is mapped to /dev/ttyS2
• COM3 is mapped to /dev/ttyS3
• COM4 is mapped to /dev/ttyS4
Posted by Uli Köhler in Windows

## How to check if your filesystem is mounted in noatime, relatime or strictatime mode

If you need to use a software that depends on your filesystem storing the last access time of a file (atime), you can use this script to check if your filesystem is mounted in noatime, strictatime or relatime mode.

This script works on both Linux and Windows.

On Linux, you can simply run this

wget -qO- https://techoverflow.net/scripts/check-atime.py | python3

Python 2 version (pythonclock.org !)

wget -qO- https://techoverflow.net/scripts/check-atime.py | python

Note that the script will check for the atime mode in whichever directory you run the script in.

In case you need to check the atime mode of a specific drive (C:, D:, …), download, the script, place it in that directory and run it from there.

This script will print one of three messages:

• Your filesystem is mounted in NOATIME mode – access times will NEVER be updated automatically
• Your filesystem is mounted in RELATIME mode – access times will only be updated if they are too old
• Your filesystem is mounted in STRICTATIME mode – access times will be updated on EVERY file access

On Linux, the default is relatime whereas on Windows the default is strictatime.

Sourcecode of the script:

#!/usr/bin/env python3
"""
This utility script checks which atime mode (strictatime, relatime or noatime)
is in use for the current filesystem
"""
import os
import time
from datetime import datetime

def datetime_to_timestamp(dt):
return time.mktime(dt.timetuple()) + dt.microsecond/1e6

def set_file_access_time(filename, atime):
"""
Set the access time of a given filename to the given atime.
atime must be a datetime object.
"""
stat = os.stat(filename)
mtime = stat.st_mtime
os.utime(filename, (datetime_to_timestamp(atime), mtime))

def last_file_access_time(filename):
"""
Get a datetime() representing the last access time of the given file.
The returned datetime object is in local time
"""
return datetime.fromtimestamp(os.stat(filename).st_atime)

try:
# Create test file
with open("test.txt", "w") as outfile:
outfile.write("test!")
time.sleep(0.1)
# Read & get first atime
with open("test.txt") as infile:
atime1 = last_file_access_time("test.txt")
time.sleep(0.1)
with open("test.txt") as infile:
atime2 = last_file_access_time("test.txt")
# Set OLD atime for relatime check!
set_file_access_time("test.txt", datetime(2000, 1, 1, 0, 0, 0))
# Access again
with open("test.txt") as infile:
# Different atime now
atime3 = last_file_access_time("test.txt")
# Check atime
changed_after_simple_access = atime2 > atime1
changed_after_old_atime = atime3 > atime1
# Convert mode to text and print
if (not changed_after_simple_access) and (not changed_after_old_atime):
print("Your filesystem is mounted in NOATIME mode - access times will NEVER be updated automatically")
elif (not changed_after_simple_access) and changed_after_old_atime:
print("Your filesystem is mounted in RELATIME mode - access times will only be updated if they are too old")
elif changed_after_simple_access and (not changed_after_old_atime):
print("Unable to determine your access time mode")
else: # Both updated
print("Your filesystem is mounted in STRICTATIME mode - access times will be updated on EVERY file access")
finally:
# Delete our test file
try:
os.remove("test.txt")
except:
pass

Also available on GitHub.

Posted by Uli Köhler in Linux, Python, Windows

## How to check if file access time is enabled on Windows

Open a command prompt (no admin command prompt required) and run this command:

fsutil behavior query disablelastaccess

For me, this prints

DisableLastAccess = 3  (Systemverwaltet, aktiviert)

indicating that access timestamps are activated.

Posted by Uli Köhler in Windows

## How to access Windows user directory in WSL (Windows Subsystem for Linux)

WSL (Windows Subsystem for Linux) mounts C: as /mnt/c inside the WSL system.

Therefore, you can access your Windows user’s home directory using

cd /mnt/c/Users/<username>

In order to find out what the correct <username> is (it’s not always your normal username, especially if you logged in with your Microsoft account or changed your username), run

ls /mnt/c/Users

Note that you will get a permission denied error when trying to access /mnt/c/Users/Default User and /mnt/c/Users/All Users. This is totally normal and usually does not matter.

Original source: Windows blog article

Posted by Uli Köhler in Windows

## Which version of Windows 10 am I running? Find out in 15 seconds!

To find out which version & build of Windows 10 you are running, first press Windows key + R.
This will open a command prompt:

In that dialog, enter winver:

Now press Enter (also known as Return). This will open the version information window, for example:

In that window, you can immediately see the version & build you are running, highlighted in red:

In my case that is Version 1809 and Build 17763.475.

Posted by Uli Köhler in Windows

## How to fix Linux/Windows dual boot clock shift

### Problem:

You have a dual-boot system. Every time you reboot from Linux to Windows, the time is shifted by several hours.

### Solution:

On Linux, run

sudo timedatectl set-local-rtc 1

This will configure Linux to store local time in the RTC.

See this StackOverflow post for alternate solutions

### Background:

Both Linux and Windows use the hardware clock (RTC – Real time clock) integrated into the computer hardware. However, Windows assumes that the RTC stores local time by default whereas Linux assumes the RTC stores UTC time.

Posted by Uli Köhler in Linux, Windows