使用 os.system(“bash code”) 在 Python 脚本中调用 bash 命令是一种好的风格吗?

发布于 2024-09-14 10:10:11 字数 1431 浏览 3 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

不忘初心 2024-09-21 10:10:11

首先,您的示例使用mv,它是coreutils中的程序,而不是bash。

使用 os.system() 调用外部程序被认为是糟糕的风格,因为:

  • 您正在创建特定于平台的依赖项
  • 您正在创建特定于版本的依赖项(是的,甚至 coreutils 有时也会更改!)
  • 您需要检查外部命令是否存在(并且它们位于 $PATH 中,并且可由用户执行等。)
  • 您必须使用它们的返回代码来包装命令并进行错误检查。使用语言内的错误代码或异常要好得多。 (os.system() 不允许您解析 stdout/stderr)
  • 您必须自己处理用空格引用变量(或转义它们)
  • Python 已经通过提供库为您完成了这项工作!

查找 glob,用于类似 shell 的模式匹配(通配符),以及 shutil,正如其他人已经提到的那样。否则,您需要的一切都已经在标准库中了。

import glob
import shutil

for extfile in glob.glob('*.ext'):
    shutil.move(extfile,dest)  

此外,不应使用 os.system() - 请查看 subprocess 模块。

First of all, your example uses mv, which is a program in coreutils, not bash.

Using os.system() calls to external programs is considered poor style because:

  • You are creating platform-specific dependencies
  • You are creating version-specific dependencies (Yes, even coreutils change sometimes!)
  • You need to check for the existence of external commands (and that they are in $PATH, and executable by the user etc.)
  • You have to wrap the commands with error checking using their return code. It is much nicer to use in-language error-codes or exceptions. (os.system() does not let you parse stdout/stderr)
  • You have to deal with quoting variables with spaces yourself (or escaping them)
  • Python has already done the work for you by supplying the libraries!

Look up glob, for shell-like pattern matching (globbing), and shutil, as others have already mentioned. Otherwise, everything you need is already in the standard libraries.

import glob
import shutil

for extfile in glob.glob('*.ext'):
    shutil.move(extfile,dest)  

In addition, os.system() should not be used - take a look at the subprocess module instead.

风柔一江水 2024-09-21 10:10:11

查看 Python 的 shutil 模块。它提供文件系统操作,例如移动文件。在该模块和 os 模块之间,您应该拥有所需的所有工具。由于其他人所说的原因,这比 bash 命令更可取。

Check out Python's shutil module. It offers file system operations such as moving files. Between that and the os module, you should have all the tools you need. This is preferable to the bash commands for the reasons others said.

寻找我们的幸福 2024-09-21 10:10:11

使用 Python 函数来做这类事情总是越来越好的风格。使用 Python,以独立于操作系统的方式编写脚本而不是使用 bash 并不是那么困难。

It always better and better style to use Python functions to do this kind of stuff. With Python it's not that hard to write a script in an OS-independent way instead of using bash.

反话 2024-09-21 10:10:11

为什么你应该使用纯Python的一些原因,

  1. 通过使用Python,你已经假设Python和标准库已经安装。通过在 Python 中使用 Bash 代码,您可以做出此假设,并假设 Bash 已安装并位于系统路径上。
  2. 通过使用两种语言的组合,你会让其他人更难以阅读代码(不是每个人都知道 Python Bash)。
  3. 如果你使用 Python 的方式,那么在少行之后会感觉更自然代码并不总是更好

在这种情况下,我会使用...

import os
for filename in os.listdir('.'):
  if filename.endswith('.ext'):
    os.rename(filename, os.path.join('path', 'to', 'new', 'destination', filename))

但可能有更好的方法

Some reasons why you should use pure Python,

  1. By using Python, you have already made the assumption that Python and the standard libraries are installed. By using Bash code inside of Python you are making this assumption plus the assumption that Bash is installed and on the system path.
  2. By using a combination of two languages you are making the code more difficult for others to read (not everyone knows Python and Bash)
  3. If you do it the Python way it will feel more natural before long - less lines of code is not always better

In this case, I would use ...

import os
for filename in os.listdir('.'):
  if filename.endswith('.ext'):
    os.rename(filename, os.path.join('path', 'to', 'new', 'destination', filename))

There may be better ways though

狂之美人 2024-09-21 10:10:11

这不是一个主意,因为它使您的脚本的可移植性大大降低。本机 python 脚本可以在任何安装了适当 python 库的 UNIX 或 Windows 计算机上运行。当您将 shell 命令添加到混合中时,您就会破坏它,并突然被锁定到一个更窄的子集。

有时你别无选择,但如果事情这么简单,用 python 本地编写代码会更有意义,而且启动速度也会更快(因为 python 进程不必生成新的进程) shell 只是为了执行一个命令)。

It's not idea, since it makes your script a lot less portable. A native python script can run on any unix or windows machine that has the proper python libraries installed. When you add shell commands into the mix, you break that, and suddenly are locked down to a much narrower subset.

Sometimes you don't have a choice, but if it's something as simple as that, writing the code natively in python would make a lot more sense, and also be faster to boot (since the python process won't have to spawn a new shell just to execute the one command).

临风闻羌笛 2024-09-21 10:10:11

仅引用问题就表明纯 Python 解决方案更可取。

The quoting issues alone suggest that a pure Python solution is preferable.

嘿看小鸭子会跑 2024-09-21 10:10:11

更一般地说,Python 提供了“子进程”模块,允许您运行命令并对它们的输出进行广泛的控制。它允许您“生成新进程,连接到它们的输入/输出/错误管道,并获取它们的返回代码”:

http://docs.python.org/library/subprocess.html

More generally, Python provides the 'subprocess' module that will allow you to run commands and exercise extensive control over their output. It lets you "spawn new processes, connect to their input/output/error pipes, and obtain their return codes":

http://docs.python.org/library/subprocess.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文