Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does importing subprocess change my output?

I noticed the following using Python 2.5.2 (does not occur using 2.7):

#!/usr/bin/python

import sys

for line in sys.stdin:
   print line,

Output:

$ echo -e "one\ntwo\nthree" | python test.py
$ one
$ two
$ three

as expected. However, if I import subprocess to the this script:

#!/usr/bin/python

import sys
import subprocess

for line in sys.stdin:
   print line,

Output:

$ echo -e "one\ntwo\nthree" | python test.py
$ two
$ three

What happened to the first line of output?

Update:

I think I may have discovered the root of the problem. I had a file named time.py in my cwd. A time.pyc is being created every time I run the script with subprocess imported, suggesting that ./time.py is also being imported. The script runs normally if I delete the .pyc and time.py files; however, there is still the question of why a subprocess import would cause ./time.py to be imported as well?

I have narrowed it down even further to the exact line in time.py that causes the strange behaviour. I have stripped down the working dir and file content to just that which affects the output:

test.py

#!/usr/bin/python

import sys
import subprocess

for line in sys.stdin:
   print line,

time.py

#!/usr/bin/python

import sys

for line in sys.stdin:
   hour = re.search(r'\b([0-9]{2}):', line).group(1)

Running test.py with any kind of input results in the first line of output being omitted and time.pyc being created.

like image 928
alh Avatar asked Oct 29 '12 15:10

alh


1 Answers

Sounds like your local time.py will be imported instead of the global time module. You might want to rename it, or at least start checking if it was run as a script or imported as a module.

This will prove it for you if you want to test it.

#!/usr/bin/python

import sys

# Test that script was run directly
if __name__=='__main__':
    for line in sys.stdin:
       hour = re.search(r'\b([0-9]{2}):', line).group(1)
else:
    print 'Imported local time.py instead of global time module!'
    sys.exit(1)
like image 121
vogonistic Avatar answered Sep 17 '22 12:09

vogonistic