【问题标题】:Echo Python variable in shell command [closed]shell命令中的Echo Python变量[关闭]
【发布时间】:2018-02-06 09:33:07
【问题描述】:

我有以下与 Bash 交互的 Python 函数。

如何让它使用callPopen 回显file1 和file2 的值?那么类似于echo $file1 file2 的东西是从 Python 执行到 Bash 终端上的吗?我的脚本目前比较两个文件的内容,但我想确保比较正确的文件。

def compareFiles(file1, file2)  
     result = Popen("diff " + file1 + " " + file2 + " | wc -l", shell=True, stdout=PIPE)
     if int(result) > 0:
         raise Exception("Error found")
     else:
         return 0

所以我知道我必须执行call("echo file1 file2", shell=True, stdout=PIPE) 之类的操作,但它不起作用。正确的格式是什么?

【问题讨论】:

  • 我不明白你想做什么,也不清楚你问题中的代码是如何相关的。它还包含语法错误。
  • 尝试从 Python 执行 shell 命令

标签: python bash popen


【解决方案1】:

你有文件路径作为函数的参数:file1file2

用 Python 打开并阅读它们。如果不需要,就没有理由掏钱。

with open(file1, "rb") as f:
    file1_data = f.read()

with open(file2, "rb") as f:
    file2_data = f.read()

print(file1_data)
print(file2_data)

【讨论】:

    【解决方案2】:

    如果您只想显示文件名的值,请使用:

    print(file1 + " " + file2)
    

    【讨论】: