w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Execute the shell script by passing certain parameters to it using Python?

There are two ways to pass variables to a script: as arguments, or through the environment.

Since you're trying to execute a script as if it were a giant command line (which won't actually work—especially if you're escaping your newlines as \n so the shell sees the whole thing as one line—but let's pretend it would), you can't pass arguments, so you will need to pass an environment.

This is trivial:

env = {}
subprocess.call('echo ${pp}', shell=True, env=env)

This will print out whatever was in jj[pp], and return 0.

Why? Well, in bash, ${pp} means "whatever is in the environment variable pp". And we copied every key-value pair from jj into the env environment, so the environment variable pp has whatever value was in jj[pp]. (In some cases you might want to quote things, e.g. "${pp}", but for echo there's no reason to do that, and without knowing what you're going to do in your real-life code I can't guess what you might need.)

If you actually had a script that you wanted to call, stored in a file, then of course you could pass it arguments the same way you do with any other program you run via subprocess, and inside the script you could reference them as $1, etc.

However, I don't see why you need to pass arguments to a script you're building on the fly. Just build the values into the script. While that's usually a bad idea, that's mainly because building a script on the fly is a bad idea, and you've already committed to that part for some reason. Format your strings in Python, where you have access to the full power of str.format or % (as you prefer), and the entire Python stdlib. For example:

script = 'echo {}'.format(shlex.quote(jj['pp']))
subprocess.call(script, shell=True)

Now the script doesn't have to do anything to access the value; it's hard-coded into the script.

© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.