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
It's faster,
os.system
andsubprocess.call
create new processes which is unnecessary for something this simple. In fact,os.system
andsubprocess.call
with theshell
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 liketest
).Some commands are useless in a separate processたとえば、 を実行すると
os.spawn("cd dir/")
、子プロセスの現在の作業ディレクトリは変更されますが、Python プロセスの作業ディレクトリは変更されません。os.chdir
そのためには を使用する必要があります。特別なことを心配する必要はありません解釈される文字シェルによって、 は
os.chmod(path, mode)
ファイル名が何であっても動作しますが、os.spawn("chmod 777 " + path)
のようなファイル名の場合は、 は失敗します。(引数なしで; rm -rf ~
を使用すると、この問題を回避できることに注意してください。)subprocess.call
shell
心配する必要はありませんダッシュで始まるファイル名.
os.chmod("--quiet", mode)
は という名前のファイルの権限を変更します--quiet
が、 は引数として解釈されるos.spawn("chmod 777 --quiet")
ため失敗します。これは の場合にも当てはまります。--quiet
subprocess.call(["chmod", "777", "--quiet"])
少ないクロスプラットフォームまた、シェル間の問題も、Python の標準ライブラリが対処してくれるはずです。システムに
chmod
コマンドはありますか? インストールされていますか? サポートが期待されるパラメータをサポートしていますか?os
モジュールは、可能な限りクロスプラットフォームになるように努め、それが不可能な場合はその旨を文書化します。実行中のコマンドに出力気にしているファイルについては解析する必要がありますが、移植性を気にしない場合でも、コーナーケース (スペース、タブ、改行が含まれるファイル名) を忘れてしまう可能性があるため、これは思ったよりも難しい作業です。