使用 os.system(“bash code") 在 Python 脚本中调用 bash 命令是一种很好的风格吗? [英] Is it good style to call bash commands within a Python script using os.system("bash code")?

查看:23
本文介绍了使用 os.system(“bash code") 在 Python 脚本中调用 bash 命令是一种很好的风格吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道使用 os.system() 在 Python 脚本中调用 bash 命令是否被认为是一种好风格.我也想知道这样做是否安全.

I was wondering whether or not it is considered a good style to call bash commands within a Python script using os.system(). I was also wondering whether or not it is safe to do so as well.

我知道如何在 Bash 和 Python 中实现我需要的一些功能,但在 Bash 中实现它更简单、更直观.但是,我觉得写 os.system("bash code") 很hackish.

I know how to implement some of the functionality I need in Bash and in Python, but it is much simpler and more intuitive to implement it in Bash. However, I feel like it is very hackish to write os.system("bash code").

具体来说,我想将所有以特定扩展名结尾的文件移动到一个目录中.

Specifically, I want to move all files that end with a certain extension to a directory.

在 bash 中:*mv .ext/path/to/destination在 Python(伪代码)中:对于目录中的文件:如果 file.endswith("ext"):将文件移动到目的地

In bash: *mv .ext /path/to/destination In Python (Pseudocode): for file in directory: if file.endswith("ext"): move file to destination

在这种情况下,我该怎么办?

In this case, what should I do?

推荐答案

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

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

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

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

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

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

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)  

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

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

这篇关于使用 os.system(“bash code") 在 Python 脚本中调用 bash 命令是一种很好的风格吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆