python - os.system 提示圆括号

标签 python awk paste os.system

我正在尝试将这一行包含在 python 脚本中。

!#/bin/bash/env python

import os

os.system("paste <(awk '!/^($|[:space:]*#)/{print $0}' file1) <(awk '!/^($|[:space:]*#)/{print $0} file2) > out_file")

直接从 bash 运行该命令时完全没问题。但是,在脚本中,我得到:

sh: -c: line0: syntax error near unexpected token `('

简单使用时问题仍然存在:

os.system("paste <(cat file1) > output_file")

有什么想法吗?

最佳答案

The command is perfectly fine when run from bash directly. However, inside the script, I get:

sh: -c: line0: syntax error near unexpected token `('

这是因为在脚本内部,您使用 sh 而不是 bash 运行命令。此命令和更简单的命令都使用 bash 特定的功能。尝试运行 sh shell 并输入相同的行,您将得到相同的错误。

os.system call 没有记录它使用的 shell,因为它是:

implemented by calling the Standard C function system()

在大多数类 Unix 系统上,这会调用 sh。您可能不应该依赖它......但是您绝对不应该依赖它调用bash!

如果您想运行 bash 命令,请使用 subprocess模块,并显式运行 bash:

subprocess.call(['bash', '-c', 'paste <(cat file1) > output_file'])

我想,您可以尝试获得正确的引用来将 bash 作为 system 使用的 shell 中的子 shell 运行……但为什么要麻烦呢?

这是文档反复告诉您应该考虑使用 subprocess 而不是 os.system 的众多原因之一。

关于python - os.system 提示圆括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16013616/

相关文章:

python - 无法让 Google App Engine OAuth2-sample(适用于 Python)工作 - 400 错误 : redirect_uri_mismatch

python - 从 Kubernetes pod 将大文件上传到 Google Storage GCE

linux - 从标准输入读取粘贴命令

linux - 以 CSV 格式打印 JSON 中的所有键和值

javascript - react 路由和django url冲突

linux - 删除句点后的第一个大写单词

linux - 如何使用 awk 获取所有 A 列与 B 列对的分数的最大值和平均值?

linux - 删除文本文件的重复项并将最后一次出现的内容保留在一个输出文件中并将其他内容移动到另一个输出文件

r - sprintf ("%03d", 7) 功能的解释?

python - 更清晰的正则表达式,用于删除点或斜线之前的字符