Repository: scrapy/scrapy

Issue:
PY3: Output to stdout cause TypeError in Scrapy 1.1.0rc1
## Environment
- Mac OS X 10.10.5
- Python 3.4.2
- Scrapy 1.1.0rc1
## Steps to Reproduce
1. Save the following spider as `myspider.py`.
   
   ``` py
   import scrapy
   
   
   class BlogSpider(scrapy.Spider):
       name = 'blogspider'
       start_urls = ['https://blog.scrapinghub.com']
   
       def parse(self, response):
           yield {'title': response.css('title::text').extract_first()}
   ```
2. Run the following command.
   
   ```
   $ scrapy runspider myspider.py -o - -t jl
   ```
## Expected Results

Extracted item is written to the stdout without error.

```
$ scrapy runspider myspider.py -o - -t jl 2> /dev/null
{"title": "The Scrapinghub Blog"}
```
## Actual Results

TypeError is raised and no item is written to the stdout.

```
$ scrapy runspider myspider.py -o - -t jl 2> /dev/null
```

```
$ scrapy runspider myspider.py -o - -t jl
2016-02-07 07:48:09 [scrapy] INFO: Scrapy 1.1.0rc1 started (bot: scrapybot)
2016-02-07 07:48:09 [scrapy] INFO: Overridden settings: {'FEED_FORMAT': 'jl', 'FEED_URI': 'stdout:'}
2016-02-07 07:48:09 [scrapy] INFO: Enabled extensions:
['scrapy.extensions.logstats.LogStats',
 'scrapy.extensions.corestats.CoreStats',
 'scrapy.extensions.feedexport.FeedExporter']
2016-02-07 07:48:09 [scrapy] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
 'scrapy.downloadermiddlewares.retry.RetryMiddleware',
 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
 'scrapy.downloadermiddlewares.chunked.ChunkedTransferMiddleware',
 'scrapy.downloadermiddlewares.stats.DownloaderStats']
2016-02-07 07:48:09 [scrapy] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
 'scrapy.spidermiddlewares.referer.RefererMiddleware',
 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
 'scrapy.spidermiddlewares.depth.DepthMiddleware']
2016-02-07 07:48:09 [scrapy] INFO: Enabled item pipelines:
[]
2016-02-07 07:48:09 [scrapy] INFO: Spider opened
2016-02-07 07:48:09 [scrapy] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2016-02-07 07:48:09 [scrapy] DEBUG: Crawled (200) <GET https://blog.scrapinghub.com> (referer: None)
2016-02-07 07:48:09 [scrapy] DEBUG: Scraped from <200 https://blog.scrapinghub.com>
{'title': 'The Scrapinghub Blog'}
2016-02-07 07:48:09 [scrapy] ERROR: Error caught on signal handler: <bound method FeedExporter.item_scraped of <scrapy.extensions.feedexport.FeedExporter object at 0x1108c05c0>>
Traceback (most recent call last):
  File "/private/tmp/scrapy1.1/venv/lib/python3.4/site-packages/twisted/internet/defer.py", line 150, in maybeDeferred
    result = f(*args, **kw)
  File "/private/tmp/scrapy1.1/venv/lib/python3.4/site-packages/pydispatch/robustapply.py", line 55, in robustApply
    return receiver(*arguments, **named)
  File "/private/tmp/scrapy1.1/venv/lib/python3.4/site-packages/scrapy/extensions/feedexport.py", line 194, in item_scraped
    slot.exporter.export_item(item)
  File "/private/tmp/scrapy1.1/venv/lib/python3.4/site-packages/scrapy/exporters.py", line 91, in export_item
    self.file.write(to_bytes(self.encoder.encode(itemdict) + '\n'))
TypeError: must be str, not bytes
2016-02-07 07:48:09 [scrapy] INFO: Closing spider (finished)
2016-02-07 07:48:09 [scrapy] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 221,
 'downloader/request_count': 1,
 'downloader/request_method_count/GET': 1,
 'downloader/response_bytes': 37941,
 'downloader/response_count': 1,
 'downloader/response_status_count/200': 1,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2016, 2, 6, 22, 48, 9, 972031),
 'item_scraped_count': 1,
 'log_count/DEBUG': 2,
 'log_count/ERROR': 1,
 'log_count/INFO': 7,
 'response_received_count': 1,
 'scheduler/dequeued': 1,
 'scheduler/dequeued/memory': 1,
 'scheduler/enqueued': 1,
 'scheduler/enqueued/memory': 1,
 'start_time': datetime.datetime(2016, 2, 6, 22, 48, 9, 425909)}
2016-02-07 07:48:09 [scrapy] INFO: Spider closed (finished)
```

Note:
- Using the other output types, jsonlines, json, csv, pickle and marshal also cause the same error, but output type xml works fine.
- Dumping to a file, i.e. `-o somefile`, does not cause the error.
- Using Python 2.7 does not cause the error.



Discussion:

Resolving patch:
diff --git a/scrapy/extensions/feedexport.py b/scrapy/extensions/feedexport.py
--- a/scrapy/extensions/feedexport.py
+++ b/scrapy/extensions/feedexport.py
@@ -10,6 +10,7 @@
 import posixpath
 from tempfile import TemporaryFile
 from datetime import datetime
+import six
 from six.moves.urllib.parse import urlparse
 from ftplib import FTP
 
@@ -58,7 +59,9 @@ def _store_in_thread(self, file):
 @implementer(IFeedStorage)
 class StdoutFeedStorage(object):
 
-    def __init__(self, uri, _stdout=sys.stdout):
+    def __init__(self, uri, _stdout=None):
+        if not _stdout:
+            _stdout = sys.stdout if six.PY2 else sys.stdout.buffer
         self._stdout = _stdout
 
     def open(self, spider):


Test patch: