Subprocess.run


In [1]:
import subprocess as sp

In [25]:
sp.run(['ls', '-a'])


Out[25]:
CompletedProcess(args=['ls', '-a'], returncode=0)

In [26]:
p = sp.run(['ls', '-ap'], stdout=sp.PIPE)

In [27]:
print(p.stdout.decode())


./
../
.ipynb_checkpoints/
Misc.ipynb
PEP-448.ipynb
PEP-465.ipynb


In [32]:
p = sp.run(['ls', 'T___T'])
p.returncode


Out[32]:
1

In [34]:
p = sp.run(['ls', 'T___T'], check=True)


---------------------------------------------------------------------------
CalledProcessError                        Traceback (most recent call last)
<ipython-input-34-a518307a790d> in <module>()
----> 1 p = sp.run(['ls', 'T___T'], check=True)

/Users/liang/.pyenv/versions/miniconda3-3.16.0/envs/sci35/lib/python3.5/subprocess.py in run(input, timeout, check, *popenargs, **kwargs)
    709         if check and retcode:
    710             raise CalledProcessError(retcode, process.args,
--> 711                                      output=stdout, stderr=stderr)
    712     return CompletedProcess(process.args, retcode, stdout, stderr)
    713 

CalledProcessError: Command '['ls', 'T___T']' returned non-zero exit status 1

In [42]:
p = sp.run(['touch', '/dev/relationship'], stderr=sp.PIPE)

In [41]:
p.stderr


Out[41]:
b'touch: /dev/relationship: Permission denied\n'

Byte formatting


In [43]:
'(%(eye)s%(nose)s%(eye)s)' % {'nose': '.', 'eye': '^'}


Out[43]:
'(^.^)'

In [44]:
b'(%(eye)s%(nose)s%(eye)s)' % {b'nose': b'.', b'eye': b'^'}  # using %s in bytes is deprecated (= %b)


Out[44]:
b'(^.^)'

In [ ]:
b'(%(eye)b%(nose)b%(eye)b)' % {b'nose': b'.', b'eye': b'^'}

In [ ]:
b'The unicode of kanji %a' % "漢字"

In [ ]:
b'The unicode of kanji %r' % "漢字"  # using %r in bytes is deprecated (= %a)

In [ ]:
b'The unicode of kanji %b' % repr("漢字").encode('ascii', 'backslashreplace')

In [ ]:
b'The unicode of kanji %b' % "漢字".encode('utf8')

In [ ]:
b'The unicode of kanji \xe6\xbc\xa2\xe5\xad\x97'.decode('utf8')

In [45]:
b = 'Hello 你好'.encode()
b


Out[45]:
b'Hello \xe4\xbd\xa0\xe5\xa5\xbd'

In [46]:
b.hex()


Out[46]:
'48656c6c6f20e4bda0e5a5bd'

In [47]:
bytes.fromhex(
    # H  e  l  l  o 
    '48 65 6C 6C 6F 20'
    #    你     好
    'E4BDA0 E5A5BD'
).decode()


Out[47]:
'Hello 你好'

In [48]:
b'({0}{1}{0})'.format('^', '.')


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-48-f1ae184c305e> in <module>()
----> 1 b'({0}{1}{0})'.format('^', '.')

AttributeError: 'bytes' object has no attribute 'format'

In [ ]: