# -*- coding: utf-8 -*- from __future__ import unicode_literals import argparse import ctypes import subprocess parser = argparse.ArgumentParser(description='test') parser.add_argument('-f', help = 'folder') args = parser.parse_args() path = args.f if ctypes.windll.shell32.IsUserAnAdmin() != 0: print 'You admin\n' output = subprocess.check_output(['takeown', '/F', path, '/R', '/A']) print output output2 = subprocess.check_output(['icacls', path, '/grant:r', 'Администраторы:F']) print output2 else: print 'You not admin' exit(0) - about display: Problems with Python 2.7 encoding - jfs
1 answer
Why UnicodeEncodeError when calling subprocess.check_output ()
Traceback indicates that subproces.check_output() calls subprocess.Popen , which on Windows calls _subprocess.CreateProcess on Python 2 .
Thanks to the from __future__ import unicode_literals directive: your 'abc' has an unicode type (Python 2).
sp_CreateProcess converts a unicode argument to bytes ( char* ), using the 'z' format , which uses the default encoding ( sys.getdefaultencoding() == 'ascii' on Python 2). See parsing arguments and building values .
Since CreateProcessA () WinAPI (not Unicode) is used on Windows in Python 2, before passing to the subprocess, try to encode the non-ascii arguments using ANSI codepage:
args = [u'icacls', path, u'/grant:r', u'Администраторы:F'] args = [arg.encode(sys.getfilesystemencoding()) for arg in args] subprocess.check_call(args) Why crackers in traceback
In Python 2, 'abc' string constant (string literal) is a sequence of bytes representing the characters written in the source code, in the encoding indicated at the top of the file ( # -*- coding: utf-8 -*- - PEP 263 encoding declaration ). from __future__ import unicode_literals directive turns 'abc' (bytes) into u'abc' (unicode).
Crawlers can appear when text encoded in one encoding is shown using a different (incompatible) encoding:
>>> print(u'Администраторы:F'.encode('utf-8').decode('cp866')) ╨Р╨┤╨╝╨╕╨╜╨╕╤Б╤В╤А╨░╤В╨╛╤А╤Л:F The source code (utf-8) is output to the console as bytes directly, without recoding, (cp866 here), so you see cracks - this can be considered a bug in Python 2.
