从 bash 转换为 python 的代码中存在语法错误

Syntax error in code converted from bash to python

我是python的新手。我在 bash 中有代码需要将其转换为 python,对转换器感到厌倦但出现语法错误。如果有人帮助我发现错误,将会非常有帮助!

错误:

File "cp_file.py", line 75
    print(myfilename.val)
  SyntaxError : Invalid Syntax

如果有人将以下 bash 代码转换为 python 而不帮助我发现错误,将会非常有帮助!

Bash 代码:

grep " 200 " /var/log/ba/access.log |awk '{print }'|sort|uniq  > /tmp/read_log.txt

for i in $(cat /tmp/read_log.txt); do
        echo $i
        myfilename="$(echo ${i##*/})"
        echo $myfilename
        wget http://mydata.na.xyz/$i
        curl -X POST -d @$myfilename http://xyz.xyz/ba/$i
done

Python 代码:

#! /usr/bin/env python
from __future__ import print_function
import sys,os,subprocess
class Bash2Py(object):
  __slots__ = ["val"]
  def __init__(self, value=''):
    self.val = value
  def setValue(self, value=None):
    self.val = value
    return value

def GetVariable(name, local=locals()):
  if name in local:
    return local[name]
  if name in globals():
    return globals()[name]
  return None

def Make(name, local=locals()):
  ret = GetVariable(name, local)
  if ret is None:
    ret = Bash2Py(0)
    globals()[name] = ret
  return ret

def Str(value):
  if isinstance(value, list):
    return " ".join(value)
  if isinstance(value, basestring):
    return value
  return str(value)

def Array(value):
  if isinstance(value, list):
    return value
  if isinstance(value, basestring):
    return value.strip().split(' ')
  return [ value ]

_rc0 = _rcr1, _rcw1 = os.pipe()
if os.fork():
    os.close(_rcw1)
    os.dup2(_rcr1, 0)
    _rcr2, _rcw2 = os.pipe()
    if os.fork():
        os.close(_rcw2)
        os.dup2(_rcr2, 0)
        _rcr3, _rcw3 = os.pipe()
        if os.fork():
            os.close(_rcw3)
            os.dup2(_rcr3, 0)
            subprocess.call("uniq",shell=True,stdout=file("/tmp/read_log.txt",'wb'))

        else:
            os.close(_rcr3)
            os.dup2(_rcw3, 1)
            subprocess.call(["sort"],shell=True)
            sys.exit(0)

    else:
        os.close(_rcr2)
        os.dup2(_rcw2, 1)
        subprocess.call(["awk","{print }"],shell=True)
        sys.exit(0)

else:
    os.close(_rcr1)
    os.dup2(_rcw1, 1)
    subprocess.call(["grep","200","/var/log/ba/access.log"],shell=True)
    sys.exit(0)

for Make("i").val in Array(os.popen("cat /tmp/read_log.txt").read().rstrip("\n")):
    print(i.val)
    Make("myfilename").setValue(os.popen("echo "+str(i.val##*/)).read().rstrip("\n"))
    print(myfilename.val)
    subprocess.call(["wget","http://xyz.xyz/"+str(i.val)],shell=True)
    subprocess.call(["curl","-X","POST","-D","@"+str(myfilename.val),"http://xyz.xyz/ba/"+str(i.val)],shell=True)

那个自动生成的 Python 代码太可怕了。坚持使用 Bash 会好得多。但最好是使用人类理解将您的代码实际迁移到 Python。例如,只取这一部分:

grep " 200 " /var/log/ba/access.log | awk '{print }'|sort|uniq  > /tmp/read_log.txt

在 Python 中类似于:

with open('/var/log/ba/access.log') as infile, open('/tmp/read_log.txt', 'w') as outfile:
    results = set()
    for line in infile:
        if ' 200 ' in line:
            tokens = line.split()
            results.add(tokens[6]) # 7th token
    for result in sorted(results):
        print >>outfile, result

对于 HTTP 部分,使用 Python 模块 requests。它易于使用。您很可能不再需要 outfile——您可以直接使用 for result in sorted(results) 来发出 HTTP 请求。

首先不要使用 for 读取文件行,而是使用 while。 See here why

这是一个非常小的脚本,在 python 中重写比使用您的转换器更容易。

如果赶时间并且真的需要 python 中的脚本,您可以在 python 中使用 linux 命令,这不是最好的方法,但对于需要的人来说更快捷、更容易不知道 python

import subprocess
p = subprocess.Popen(["curl","POST","-X", "YOUR_URL"], 
stdout=subprocess.PIPE,  shell=True) (output, err) = p.communicate()