1

If I run this

test -d a

in Linux command line, it returns nothing and prints no error even if directory a doesn't exist, because the result is returned via exit code.

But if I want to grab this exit code with Python, I get

import subprocess
subprocess.call('test -d a')

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/opt/anaconda3/envs/python27/lib/python2.7/subprocess.py", line 168, in call
    return Popen(*popenargs, **kwargs).wait()
  File "/opt/anaconda3/envs/python27/lib/python2.7/subprocess.py", line 390, in __init__
    errread, errwrite)
  File "/opt/anaconda3/envs/python27/lib/python2.7/subprocess.py", line 1025, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

How to overcome this? Changing command text is not allowed, anly python caller code should change. It shoudl return 0 or 1 depending on directory existence as described in manual.

Dims
  • 47,675
  • 117
  • 331
  • 600

1 Answers1

0

Your issue might be that Python cannot find test -d a rather than test failing and subprocess.call identifying the error and rasing an seemingly appropriate OSError exception. See the exceptions region of the subprocess.call/Popen docs. The right way to call it would be subprocess.call(['test', '-d', 'a'])

Horia Coman
  • 8,681
  • 2
  • 23
  • 25