Clifford Piehl
Clifford Piehl

Reputation: 535

Running Python with VS Code - The basics

Unfortunately I am but another noob who is frustrated by my lack of understanding what are likely very basic concepts... So here it goes! I simply want to understand the concept behind me running the windows python version command in the .py file, and it not working, versus the same command being run directly in the command prompt, and the command working. To illustrate:

enter image description here I write the command in the editor and run the script. The result is an error.

enter image description here I run the same command directly into the terminal within VS Code. It works. What concept am I missing here? I can print 'Hello World', but I cannot run the version command?

Upvotes: 0

Views: 188

Answers (2)

frmbelz
frmbelz

Reputation: 2553

VS Code terminal is a shell CLI (command line interface) providing interface to OS (in this case PS in VS Code terminal is a Windows PowerShell). Inside Python .py file you can not run shell commands as-is from command-line. Still shell commands can be run inside python scripts, for example, inside .py file

import os
# older way, os.system deprecated
print("%d" % os.system("python --version"))

# it's replacement subprocess
import subprocess
py_v1 = subprocess.run(["py", "-3", "--version"])
print("%d" % py_v1.returncode)

py_v2 = subprocess.run(["python", "--version"])
print("%d" % py_v2.returncode)

py_v3 = subprocess.Popen(["python", "--version"])
print(py_v3.communicate())

Output (more on subprocess)

Python 3.7.4
0
Python 3.7.4
0
Python 3.7.4
0
Python 3.7.4
(None, None)

Upvotes: 0

Arvind
Arvind

Reputation: 1016

You are mixing OS commands with Python.

To run anything with Python, you must follow and use its programming guidelines and APIs https://docs.python.org/3/

To print Python version write this in your script:

import platform
print(platform.python_version())

To print python version on windows cmd run:

  python --version

or you are using:

  py -3 version

Upvotes: 2

Related Questions