开发者

Calling python script from awk

开发者 https://www.devze.com 2023-03-03 01:35 出处:网络
most of the solutions out there call awk from python. But i want to do it the other way round. I have a python script that extracts information from a file. However said filename is referenced in a co

most of the solutions out there call awk from python. But i want to do it the other way round. I have a python script that extracts information from a file. However said filename is referenced in a column of the awk script.

How do i pass python the argument "%s20s", filename and get the input from the standard output? i want to add the output as several columns m开发者_StackOverflow中文版ore.

thanks for your examples

Cheers


The awk variable FILENAME gives the name of the current file being processed (or '-' if stdin). However, this is not available in the BEGIN block, but you can use ARGV[1] instead (assuming you are only passing one filename):

#!/bin/awk -f

BEGIN {
    cmd = "./myscript.py '\"%s20s\"' " ARGV[1]
    print cmd
    cmd  | getline var       
    print var
}

The python script (py3) I used for testing was:

#!/usr/bin/python

import sys
print(sys.argv)

So I get the following output:

/home/user1> runit.awk afile
./myscript.py "%s20s" afile
['./myscript.py', '"%s20s"', 'afile']


You can call external commands using the system function. Does that solve your problem?

$ awk 'BEGIN { system("echo something") }'
something

But that only provides the return code. If you need to capture stdin you can do this:

$ awk 'BEGIN { "echo something" | getline; print "output: "$0 }'
output: something

Getline works line-by-line so if you want multiple lines:

$ awk 'BEGIN { while ("cat multi_line_file" | getline) { print "output: "$0 } }'
output: line 1
output: line 2
output: line 3
0

精彩评论

暂无评论...
验证码 换一张
取 消