使用变量执行commands.getoutput

时间:2018-05-17 10:04:32

标签: python scripting

我试图在python中执行命令,并且我给这个命令一个变量

commands.getoutput("cat '" +dir_log+ "'")

dir_log是一个变量,但是python并没有将它作为变量。

2 个答案:

答案 0 :(得分:1)

来自official docs

  

从版本2.6开始不推荐使用:已在Python 3中删除commands模块。请改用subprocess模块。

所以,除非你使用Python 2.5或更早版本,我怀疑,使用subprocess模块:

import subprocess

dir_log = "/path/to/file"
output = subprocess.check_output(["cat", dir_log])

subprocess模块将为您处理转义和参数链接。

唯一的问题仍然是 - 你在"是什么意思;但是python并没有将它作为变量" ?如果dir_log在本地上下文中可用,则其值将传递给cat

当您可以直接在Python中加载内容时,将cat作为子进程调用是没有意义的,因为:

with open(dir_log, "r") as f:
    file_contents = f.read()

答案 1 :(得分:0)

在python 2中,尝试:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="slide-trigger">
  <div class="slide">
    <p>Slidey stuff</p>
  </div>
</div>

<div class="slide-trigger">
  <div class="slide">
    <p>More slidey stuff</p>
  </div>
</div>

在python 3中,不建议使用command模块,而WITH orig_result_set AS ( select distinct a.customer_id, a.name, pay_type from table a left join table b on a.customer_id= b.id left join table c on c.id = b.pay_id where b.status = 'Done' ), exclude_late_payments AS ( SELECT DISTINCT customer_id FROM orig_result_set WHERE pay_type = 'late' ), on_time_payments AS ( SELECT customer_id, name, pay_type FROM orig_result_set WHERE customer_id NOT IN exclude_late_payments ) SELECT * FROM on_time_payments command='cat {}'.format(dir_log) commands.getoutput(command) 等效,请尝试:

subprocess.getoutput