2

Python on Windows does not use normal STDOUT, so what is going on here?

python --version
Python 2.7.15

shows a version! But I can't capture it!

python --version > temp.txt
Python 2.7.15
type temp.txt

NOTHING!

The issue is, I need to do logic depending on the Python version (from JavaScript) and it's been pretty hopeless so far.

Gant Laborde
  • 6,484
  • 1
  • 21
  • 30

2 Answers2

3

Try redirecting stderr to stdout at the same time you redirect stdout to a file:

python --version 1>temp.txt 2>&1

Julio
  • 5,208
  • 1
  • 13
  • 42
  • So, I need this to go to STDOUT. Sending to the file like you have works on the file, but if I try to then get it in STDOUT in the same go, like : `python --version 1>temp.txt 2>&1 | type temp.txt` my output will get swallowed. – Gant Laborde Aug 16 '18 at 23:46
  • Why not `python --version 1>temp.txt 2>&1` first, and then on a new line (new command) do: `type temp.txt`? – Julio Aug 16 '18 at 23:49
  • The library I'm using checks one command on Linux/Windows/Mac. Making a special case for it to run two commands just for some wonky windows bug is possible but not desirable. Better, would be python + windows behaving properly, second case would be a way to fix up a single command to give me a valid STDOUT. Worst case is upstream logic for something problematic like we have here. – Gant Laborde Aug 16 '18 at 23:52
  • 1
    I do't whink this is a windows bug. That doesn't work with linux either: `echo hello >/tmp/test | cat` returns nothing. However `echo hello >/tmp/test ; cat /tmp/test` does (two commands on same new line) For windows you could try with `&` or `&&` (`&` always executes right command and `&&` executes if first command ends ok) So `python --version 1>temp.txt 2>&1 & type temp.txt` for example – Julio Aug 16 '18 at 23:57
1

You can use a Python command to print the version info to stdout:

> python -c "import sys;print(sys.version)" > temp.txt

After this command, temp.txt will contain the version information.

> type temp.txt
2.7.15 |Anaconda, Inc.| (default, May  1 2018, 18:37:09) [MSC v.1500 64 bit (AMD64)]

If you wanted to get fancier, you could use sys.version_info to extract only specific part of the version, like the major number as explained in https://stackoverflow.com/a/9079062/7517724. Using the following line will store only the major version number in temp.txt:

> python -c "import sys;print(sys.version_info[0])" > temp.txt
> type temp.txt
2
Craig
  • 4,605
  • 1
  • 18
  • 28