这是好作风利用使用os.system调用Python脚本的bash内部命令("庆典code")? [英] Is it good style to call bash commands within a Python script using os.system("bash code")?

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

问题描述

我不知道它是否被认为是一个良好的作风使用使用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中的功能,但它更简单,更直观地实现它在猛砸。不过,我觉得这是非常的hackish要使用os.system写(庆典code)。

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 /路径/要/目的
在Python(伪code):
 在目录中的文件:
    如果file.endswith(外部):
        移动文件到目的地

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和用户等可执行程序。)

  • 您必须使用他们返回code错误检查包裹的命令。这是更漂亮使用的语言错误 - codeS或异常。 (使用os.system()不会让你解析标准输出/标准错误)

  • 您必须处理引用变量用空格自己(或转义)

  • 的Python已经通过提供的库为你做的工作!

查找水珠,为壳状模式匹配(通配符)和 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()不应该使用 - 看看在模块来代替。

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

这篇关于这是好作风利用使用os.system调用Python脚本的bash内部命令("庆典code")?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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