0

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?

1
  • 1
    Because you are trying to run a shell command with the Python interpreter. That won't work. Commented Oct 3, 2021 at 23:16

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

3 Comments

Ah! I think I get it now. The command I was using wasn't even python! I got it from VS code's tutorial site. They are giving me OS commands, not python.. So I can still run python script so long as they are valid commands?
Yes OS commands can be used to install packages etc. But inside Python it must adhere to its API.
Interesting, with a conda environment activated on VSCode terminal or Anaconda command line python --version shows Python version of that environment while py -3 --version shows the base default Python version...
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.