WhiteMask
WhiteMask

Reputation: 646

Call Programs with Python Output

I want to call the c program display_output with python generated arguments, however I'm not sure how to formulate the syntax. I tried this

./display_output (python -c "print 'A' * 20")

but I get

bash: syntax error near unexpected token `python'

I suppose this goes along with my original question and could help me out with that. The only way I could find to try running python cmd line output as a bash command was by appending | bash to the command. However, is there a better way to do this?

(python -c "print 'ls'") | bash

I clearly don't know my way around Bash, but I was certain there was a more appropraite way to do this.

Upvotes: 1

Views: 56

Answers (1)

glenn jackman
glenn jackman

Reputation: 247022

When bash sees an open parenthesis at a place where a command can be, it will launch a subshell to run the enclosed commands. Where you currently have them is not a place where a command can go. What you want instead is command substitution

./display_output $(python -c "print 'A' * 20") 
# ...............^

You will get into trouble if any of the arguments generated contain whitespace (obviously not the case for this toy example.

To generate a string of 20 "A"s in bash, you would write:

a20=$(printf "%20s" "")    # generate a string of 20 spaces   
# or, the less readable but more efficient: printf -v a20 "%20s" ""
a20=${a20// /A}            # replace all spaces with A's

The last line is pattern replacement in shell parameter expansion

Upvotes: 2

Related Questions