'Not able to run command via wsl.exe

I'm trying to run this commands from a python script:

def raw(path_avd_py, path_avd, snp_name, out_file):
    if OS == 'Windows':
        cmd_raw = f"wsl.exe -e sh -c 'python3 {path_avd_py} -a {path_avd} 
        -s {snp_name} -o {out_file}'"
    else:
        cmd_raw = f'python3 {path_avd_py} -a {path_avd} -s {snp_name} -o {out_file}'
    subprocess.Popen(cmd_raw, shell=True)
    time.sleep(25)
    return None


def idiffer(i_path, raw_1, raw_2, path, state):
    if OS == 'Windows':
        cmd_idiff = f"wsl.exe -e sh -c 'python3 {i_path} {raw_1} {raw_2}'"
    [...]
    file = os.path.join(path, f'{state}.idiff')
    with open(file, 'w') as f:
        subprocess.Popen(cmd_idiff, stdout=f, text=True)

If im executing cmd_raw with subprocess.run from a python-shell (Powershell), things are working. If im try running this via script, this exception occurs, using different shells:

-e sh: avdecrypt-master\avdecrypt.py: 1: Syntax error: Unterminated quoted string

-e bash: avdecrypt-master\avdecrypt.py: -c: line 0: unexpected EOF while looking for matching `'' avdecrypt-master\avdecrypt.py: -c: line 1: syntax error: unexpected end of file

I already tried os.system, os.run([list]) no change. Thanks for the help!



Solution 1:[1]

For those who have a similar question, I found a solution, which is working for me: Apparently calling scripts with some argv has to be in one single quotation mark and can be executed via run (in my case important, because the process has to be terminated). This leads to a form like:

cmd = ['wsl.exe', '-e', 'bash', '-c', '-a foo -b bar [...]']
subprocess.run(cmd, shell=True)

Lib shlex is helping here and formatting the strings like subprocess is needing it:

cmd_finished = shlex.split(cmd)

https://docs.python.org/3/library/shlex.html

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 avatrax