0

I am creating a script with Python3 that runs a couple of Linux terminal commands for me (https://github.com/stefanrows/ceos3c-baseline-installer)

Everything works so far except the following line:

os.system('sudo -u {} sudo sh -c 'echo "deb [arch=amd64 signed-by=/usr/share/keyrings/packages.microsoft.gpg] https://packages.microsoft.com/repos/vscode stable main" > /etc/apt/sources.list.d/vscode.list'.format(user))

I am pretty sure it has something to do with character escaping, but I don't know where exactly I have to change something.

Would be great if someone could point me in the right direction!

Stefan Rows
  • 67
  • 10
  • 3
    Better use `subprocess.run()` instead of `os.system()`. – Mike Müller Feb 06 '20 at 10:48
  • 1
    The syntax highlighting should show you: Your single quotes inside the string need to be escaped with a backslash; `-c \'echo`. In addition, your second single quote needs to be doubled (and the first one escaped). – L3viathan Feb 06 '20 at 10:49
  • @MikeMüller can you elaborate on why this is better to use than os? – Stefan Rows Feb 06 '20 at 10:56
  • 1
    From the docs: "The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several older modules and functions:" `os.system` `os.spawn*` – Mike Müller Feb 06 '20 at 11:07
  • 1
    More details why `subproess` should be used https://www.python.org/dev/peps/pep-0324/ – Mike Müller Feb 06 '20 at 11:24

1 Answers1

0

@L3viathan provided the answer.

Had to escape a single quote at the beginning and escape + add another on the end. Thanks!

os.system('sudo -u {} sudo sh -c \'echo "deb [arch=amd64 signed-by=/usr/share/keyrings/packages.microsoft.gpg] https://packages.microsoft.com/repos/vscode stable main" > /etc/apt/sources.list.d/vscode.list\''.format(user))
Stefan Rows
  • 67
  • 10