Skip to content

Commit

Permalink
Support the os.PathLike protocol
Browse files Browse the repository at this point in the history
  • Loading branch information
jaden-young committed Feb 9, 2018
1 parent 0d8d594 commit c77e935
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
1 change: 1 addition & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ python:
- "3.3"
- "3.4"
- "3.5"
- "3.6"
- "pypy2.7-5.8.0"
script:
- python test/test.py
Expand Down
6 changes: 6 additions & 0 deletions pydub/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,12 @@ def _fd_or_path_or_tempfile(fd, mode='w+b', tempfile=True):
if isinstance(fd, basestring):
fd = open(fd, mode=mode)

try:
if isinstance(fd, os.PathLike):
fd = open(fd, mode=mode)
except AttributeError:
pass

return fd


Expand Down
25 changes: 25 additions & 0 deletions test/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,31 @@ def test_audio_segment_from_mp3(self):
self.assertTrue(seg1._data == seg2._data)
self.assertTrue(len(seg1) > 0)

def test_audio_segment_from_path_like_object(self):
try:
# The import of fspath() is unusd, but is what will actually raise
# the ImportError. os.fspath() was introduced in python 3.6, while
# pathlib came in 3.4. While we could call str() to get a string
# representation of pathlib objects when they're passed to
# AudioSegment.from_file(), giving support to 3.4 and 3.5, it is
# safe to assume that users of 3.4 or 3.5 that use Path objects are
# aware of the limitations, and are used to calling str()
# themselves.
from os import fspath
from pathlib import Path

mp3_path_obj = Path(self.mp3_path)

seg1 = AudioSegment.from_file(self.mp3_path)
seg2 = AudioSegment.from_file(mp3_path_obj)

self.assertEqual(len(seg1), len(seg2))
self.assertTrue(seg1._data == seg2._data)
self.assertTrue(len(seg1) > 0)
except ImportError:
# We're on python < 3.6, so there's nothing to test.
pass


test1wav = test4wav = test1 = test2 = test3 = testparty = testdcoffset = None

Expand Down

0 comments on commit c77e935

Please sign in to comment.