0

I'm redirecting stderr to a file with

python foo.py 2> stderror.txt

Once the script is partway done, I want to move stderror.txt with

subprocess.call(['cp', 'stderror.txt', 'destination.txt'])

My question - what if I redirected stderr to results/stderror.txt? Is there a way to programmatically get the destination of a redirect from within the script?

(Note: I know that this isn't really the way to solve my problem. Just curious.)

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
mfsiega
  • 2,852
  • 19
  • 22

1 Answers1

2

One possible way is to read the link /proc/<pid>/fd/2:

os.readlink("/proc/%d/fd/2" % os.getpid())

A shortcut is to use /proc/self/fd/2. In the unredirected case, you'll get some special file in /dev, usually a pseudo terminal. For other OSes, see this related question.

Community
  • 1
  • 1
Phillip
  • 13,448
  • 29
  • 41