简体   繁体   中英

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.

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)

print line, before 2.7 did not put out a newline so it overwrote the first line. Lose the comma and the result will be the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM