0

i want to see some info and get info about my os with python as in my tutorial but actually can't run this code:

import os
F = os.popen('dir') 

and this :

F.readline()
' Volume in drive C has no label.\n'
F = os.popen('dir')               # Read by sized blocks
F.read(50)
' Volume in drive C has no label.\n Volume Serial Nu'

os.popen('dir').readlines()[0]    # Read all lines: index
' Volume in drive C has no label.\n'
os.popen('dir').read()[:50]       # Read all at once: slice
' Volume in drive C has no label.\n Volume Serial Nu'

for line in os.popen('dir'):      # File line iterator loop
...     print(line.rstrip())

this is the the error for the first on terminal, (on IDLE it return just an '

f = open('dir') Traceback (most recent call last): File "", line 1, in FileNotFoundError: [Errno 2] No such file or directory: 'dir'

I know on mac it should be different but how? to get the same result using macOS sierra.

Terry Jan Reedy
  • 18,414
  • 3
  • 40
  • 52
  • I accidentally removed the assignment in `>>> F = os.peoen('dir')` while editing to fix the code block display of the IDLE session. Someone else unfortunately is trying to remove the IDLE session part completely (OP specifically mentions IDLE). So I have to wait for that to get rejected before fixing the editing mistake. – tdelaney Oct 15 '16 at 18:53
  • IDLE is not relevant to Python reporting an error when running Windows-specific code on OSX. – Terry Jan Reedy Oct 16 '16 at 00:43

3 Answers3

0

The code you are following looks like it was written for Windows. popen runs a command -- but there is no dir command on a Mac. dir in DOS shows you files in a directory (folder); the equivalent command on a Mac is ls.

lungj
  • 721
  • 5
  • 16
0

open and os.popen are entirely different*.

The first one just opens a file (by default for reading), but the second one runs a command in your shell and gives you the ability to communicate with it (e.g. get the output).

So, given that open opens the file for reading when you supply only the file's name, if such a file doesn't exist, it raises an error, which is the case here.

os.popen executes the given command on your computer as if you typed it in the terminal.


* There exists another function with a similar name: os.open, which is, again, different from the ones mentioned earlier.

Community
  • 1
  • 1
ForceBru
  • 43,482
  • 10
  • 63
  • 98
0

os.popen executes a program and returns a file-like object to read the program output. So, os.popen('dir') runs the dir command (which lists information about your hard drive) and gives you the result. open opens a file on your hard drive for reading.

Your problem is that there is no file named dir. You likely wanted f = os.popen(dir) MAC is different than windows and the base directory listing command is ls. But most unixy systems have a dir command that lists files in a different format, so it should work for you.

tdelaney
  • 73,364
  • 6
  • 83
  • 116