Why use Python's os module methods instead of executing shell commands directly?

前端 未结 6 992
耶瑟儿~
耶瑟儿~ 2021-01-29 17:58

I am trying to understand what is the motivation behind using Python\'s library functions for executing OS-specific tasks such as creating files/directories, changing file attri

6条回答
  •  没有蜡笔的小新
    2021-01-29 18:48

    For a simple reason - when you call a shell function, it creates a sub-shell which is destroyed after your command exists, so if you change directory in a shell - it does not affect your environment in Python.

    Besides, creating sub-shell is time consuming, so using OS commands directly will impact your performance

    EDIT

    I had some timing tests running:

    In [379]: %timeit os.chmod('Documents/recipes.txt', 0755)
    10000 loops, best of 3: 215 us per loop
    
    In [380]: %timeit os.system('chmod 0755 Documents/recipes.txt')
    100 loops, best of 3: 2.47 ms per loop
    
    In [382]: %timeit call(['chmod', '0755', 'Documents/recipes.txt'])
    100 loops, best of 3: 2.93 ms per loop
    

    Internal function runs more than 10 time faster

    EDIT2

    There may be cases when invoking external executable may yield better results than Python packages - I just remembered a mail sent by a colleague of mine that performance of gzip called through subprocess was much higher than the performance of a Python package he used. But certainly not when we are talking about standard OS packages emulating standard OS commands

提交回复
热议问题