Skip to content
Advertisement

not able to redirect the output to a file in ipython ide

I am not able to redirect the output of dir(modulename) to a file in ipython ide. Please let me know how to do that. It works for the same for ls and other linux commands.

 In [45]: os.system('dir(socket) > socket1.txt')
 File Not Found
 Out[45]: 1

 In [46]: os.system('cat socket1.txt')
 Volume in drive C is Local Disk
 Volume Serial Number is D649-B68C

 Directory of C:UsersaryanPycharmProjectsclasses

 Out[46]: 0

In [47]: dir (socket)
Out[47]:
['AF_APPLETALK',

Advertisement

Answer

You are mixing two worlds here.

One is the Python world in which you can call Python functions (like dir()); in this world redirection is not done simply using > or similar things.

The other world is the Shell world in which you can call shell command lines (like cat socket1.txt); in this world redirection can be done using a simple > symbol (together with a file name) after the command. This world is entered using the system() call (or others from the subprocess module).

What you are now doing is using system() to enter the Shell world and then execute dir() in this world (which does not work). The redirection will work, though, so you will create a file named socket1.txt (probably empty).

Redirecting the output of a Python call is a thing not so easily done in general. Your case, however, is special: You just want to dump a Python value into a file. This is easy:

with open('socket1.txt', 'w') as out_file:
  out_file.write(str(dir(socket)))
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement