“找不到命令";使用python在os.system的参数中使用line [英] "command not found" using line in argument to os.system using python

查看:689
本文介绍了“找不到命令";使用python在os.system的参数中使用line的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python的新手,正在从事一些xyz项目,在该项目中我要进行第一天的过时报告,获取数据并将其重定向到Linux机器上的另一个文件中

I am new to python and working on some xyz project where i am taking the day-1 dated report, fetching the data and redirecting it into another file on linux machine

这是我的代码.

#!/usr/bin/python

import os

cur_date = os.popen("date -d '-1 day' '+%Y%m%d'").read()
print (cur_date)
os.system('zgrep "919535144580" /var/tmp/comp?/emse_revres_rdc.log.%s* | grep -v "RI" | cut -d "|" -f 9,10,23,24,26 | sort | uniq -c | sort -nr >> /var/tmp/Andy/test.txt'%cur_date)

它正在打印以下错误.

20180731

**gzip: /var/tmp/comp?/emse_revres_rdc.log.20180731.gz: No such file or directory
sh: line 1: 1: command not found**

但是当我在shell中执行相同操作时,它运行得很好,或者如果我手动给出日期并运行上面的命令,则它可以成功运行.

but when i am executing the same in shell it is running absolutely fine or if i manually give the date and run the above, it runs successfully.

请在同一点上提供您的建议.

Please provide your suggestions on the same.

推荐答案

*与问题无关.您用%s替换的字符串以换行符结尾,而该换行符是破坏代码的原因.

The * has nothing to do with the problem; the string you're substituting with %s ends with a newline, and that newline is what breaks your code.

使用os.popen('...').read()时,会得到... entire 输出-包括结尾的换行符,shell命令替换隐式地修剪掉了换行符.

When you use os.popen('...').read(), you get the entire output of ... -- including the trailing newline, which shell command substitutions implicitly trim.

最好的答案是用Python重写逻辑,但是这里的简单答案是使用这样的命令替换,这也避免了尝试将值传递到通过字符串替换的脚本(这是解决注入shell安全漏洞的快速方法):

The best answer would be to rewrite your logic in Python, but the easy answer here is to use such a command substitution, which also avoids trying to pass values into a script via string substitution (which is a fast route to shell-injection security bugs):

shell_script = r'''
cur_date=$(date -d '-1 day' '+%Y%m%d')

zgrep "919535144580" /var/tmp/comp?/emse_revres_rdc.log."$cur_date"* \
  | grep -v "RI" \
  | cut -d "|" -f 9,10,23,24,26 \
  | sort \
  | uniq -c \
  | sort -nr \
  >> /var/tmp/Andy/test.txt
'''

os.system(shell_script)

也就是说,如果您只想进行尽可能短的更改,请在原始代码的os.system()调用之前放置以下内容:

That said, if you're just going for the shortest change possible, put the following before your original code's os.system() call:

cur_date = cur_date.rstrip('\n')

这篇关于“找不到命令";使用python在os.system的参数中使用line的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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