代码之家  ›  专栏  ›  技术社区  ›  Chubaka

在python 3.6子进程中运行awk日期转换

  •  0
  • Chubaka  · 技术社区  · 7 年前

    我想把下面的awk行写进python

    awk -F, '{cmd="date -d \""$2"\" +%s"; cmd | getline date; printf ("%s,%d,%d\n",$1,date,$3)}' counts.csv > counts_epoch.csv 
    

    V1

    import subprocess
    
    with open("counts_epoch.csv", 'wb') as f:
        subprocess.Popen(["awk", "'{cmd="date -d \""$2"\" +%s"; cmd | getline date; printf ("%s,%d,%d\n",$1,date,$3)}'", 'counts.csv'], stdout=f)
    

    这将返回:

        subprocess.Popen(["awk", "'{cmd="date -d \""$2"\" +%s"; cmd | getline date; printf ("%s,%d,%d\n",$1,date,$3)}'", 'counts.csv'], stdout=f)
                                        ^
    SyntaxError: invalid syntax
    

    V2:

    with open("counts_epoch.csv", 'wb') as f:
        subprocess.call(["awk", '{cmd="date -d \""$2"\" +%s"; cmd | getline date; printf ("%s,%d,%d\n",$1,date,$3)}', 'counts.csv'], stdout=f)
    

    返回:

    awk: cmd. line:1: {cmd="date -d ""$2"" +%s"; cmd | getline date; printf ("%s,%d,%d
    awk: cmd. line:1:                                                            ^ unterminated string
    awk: cmd. line:1: {cmd="date -d ""$2"" +%s"; cmd | getline date; printf ("%s,%d,%d
    awk: cmd. line:1:                                                            ^ syntax error
    

    有什么建议吗?谢谢!

    1 回复  |  直到 7 年前
        1
  •  1
  •   Elias Dorneles    7 年前

    r shlex.split

    import shlex
    cmdline = r"""awk -F, '{cmd="date -d \""$2"\" +%s"; cmd | getline date; printf ("%s,%d,%d\n",$1,date,$3)}' counts.csv"""
    cmd = shlex.split(cmdline)
    

    with open("counts_epoch.csv", 'wb') as f:
        subprocess.Popen(cmd, stdout=f)