Skip to content

Commit 43af2c5

Browse files
greylitheskumar
authored andcommitted
Force environment variables to str with Python2 on Windows (theskumar#101)
* Force environment variables to str With Python2 on Windows, force environment variables to str to avoid "TypeError: environment can only contain strings " in Python's subprocess.py. * PEP8 fix * Add Python3 compatible * Fix flake8 fails with F821 * Fix flake8 fails with F821
1 parent 27afc40 commit 43af2c5

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

dotenv/compat.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
1+
import sys
12
try:
23
from StringIO import StringIO # noqa
34
except ImportError:
45
from io import StringIO # noqa
6+
7+
PY2 = sys.version_info[0] == 2
8+
WIN = sys.platform.startswith('win')
9+
text_type = unicode if PY2 else str # noqa

dotenv/main.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
import warnings
1212
from collections import OrderedDict
1313

14-
from .compat import StringIO
14+
from .compat import StringIO, PY2, WIN, text_type
1515

1616
__escape_decoder = codecs.getdecoder('unicode_escape')
1717
__posix_variable = re.compile('\$\{[^\}]*\}') # noqa
@@ -95,6 +95,12 @@ def set_as_environment_variables(self, override=False):
9595
for k, v in self.dict().items():
9696
if k in os.environ and not override:
9797
continue
98+
# With Python2 on Windows, force environment variables to str to avoid
99+
# "TypeError: environment can only contain strings" in Python's subprocess.py.
100+
if PY2 and WIN:
101+
if isinstance(k, text_type) or isinstance(v, text_type):
102+
k = k.encode('ascii')
103+
v = v.encode('ascii')
98104
os.environ[k] = v
99105

100106
return True

0 commit comments

Comments
 (0)