0


In this code, subprocess.Popen creates /tmp/test.txt with date output. Why doesn't the 2nd "print lines" work ? I would appreciate for your help.

test]# touch /tmp/test.txt
test]# ./x1.py
/tmp/test.txt
()
/tmp/test.txt
()
test]# ./x1.py
/tmp/test.txt
('Sun Jun 19 15:10:21 PDT 2016\n',)
/tmp/test.txt
()
test]# cat x1.py
#!/usr/bin/python

from subprocess import Popen, PIPE

filename = "/tmp/test.txt"

lines = tuple(open(filename, 'r'))
print filename
print  lines # this is not empty

file_ = open(filename, "w")
Popen("date", shell=True, stdout=file_)
file_.close()

lines = tuple(open(filename, 'r'))
print filename
# why is this empty even if file_ definitely created the /tmp/test.txt ?
print  lines    
test]# 
4
  • 1
    Works fine for me on ubuntu Commented Jun 19, 2016 at 22:24
  • Aside: Why are you in a root shell? Commented Jun 19, 2016 at 22:26
  • 1
    Have you considered .wait()ing for the Popen to finish before closing its stdout? Commented Jun 19, 2016 at 22:52
  • @Tadhg McDonald-Jensen, It worked. Appreciate your help Commented Jun 19, 2016 at 23:02

1 Answer 1

2

You need to .wait() for the Popen to finish before closing the stdout, otherwise you get undefined behaviour.

Popen("date", shell=True, stdout=file_).wait()
#                                       ^ add this part!

I can't say for sure how the file was written to after you tried to read from it but I imagine that is an implementation detail for your OS.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.