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

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

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 attributes, etc. instead of just executing those commands via os.system() or subprocess.call()?

For example, why would I want to use os.chmod instead of doing os.system("chmod...")?

I understand that it is more "pythonic" to use Python's available library methods as much as possible instead of just executing shell commands directly. But, is there any other motivation behind doing this from a functionality point of view?

I am only talking about executing simple one-line shell commands here. When we need more control over the execution of the task, I understand that using subprocess module makes more sense, for example.

ベストアンサー1

  1. It's faster, os.system and subprocess.call create new processes which is unnecessary for something this simple. In fact, os.system and subprocess.call with the shell argument usually create at least two new processes: the first one being the shell, and the second one being the command that you're running (if it's not a shell built-in like test).

  2. Some commands are useless in a separate processたとえば、 を実行するとos.spawn("cd dir/")、子プロセスの現在の作業ディレクトリは変更されますが、Python プロセスの作業ディレクトリは変更されません。os.chdirそのためには を使用する必要があります。

  3. 特別なことを心配する必要はありません解釈される文字シェルによって、 はos.chmod(path, mode)ファイル名が何であっても動作しますが、os.spawn("chmod 777 " + path)のようなファイル名の場合は、 は失敗します。(引数なしで; rm -rf ~を使用すると、この問題を回避できることに注意してください。)subprocess.callshell

  4. 心配する必要はありませんダッシュで始まるファイル名.os.chmod("--quiet", mode)は という名前のファイルの権限を変更します--quietが、 は引数として解釈されるos.spawn("chmod 777 --quiet")ため失敗します。これは の場合にも当てはまります。--quietsubprocess.call(["chmod", "777", "--quiet"])

  5. 少ないクロスプラットフォームまた、シェル間の問題も、Python の標準ライブラリが対処してくれるはずです。システムにchmodコマンドはありますか? インストールされていますか? サポートが期待されるパラメータをサポートしていますか?osモジュールは、可能な限りクロスプラットフォームになるように努め、それが不可能な場合はその旨を文書化します。

  6. 実行中のコマンドに出力気にしているファイルについては解析する必要がありますが、移植性を気にしない場合でも、コーナーケース (スペース、タブ、改行が含まれるファイル名) を忘れてしまう可能性があるため、これは思ったよりも難しい作業です。

おすすめ記事