简体   繁体   中英

How do I pass a variable (string) to a bash script from python and later echo it?

I wrote a script on spyder3 which calls, through function 'subprocess.call', a bash file and passes (or should do so) a variable. The problem is, not being familiar with bash coding, I don't know how to import/read this variable and (for example) print it or echo it. Here are my lines of code on spyder:

variable='test'
subprocess.call(['./path/bash_file.sh',variable])

And on the bash file:

#!/bin/sh
echo variable

But obviously something is missing, in the bash file at least(?).

either pass the variables to the bash script as arguments or environmental vars

p = subprocess.Popen(
    ("/bin/bash", "script.sh", arg1, arg2),
    ...
)
out, err = p.communicate()
custom_env = os.environ.copy()  # if you want info from wrapping env
custom_env["foo"] = arg3        # this is just a dictionary
p = subprocess.Popen(
    ("/bin/bash", "script.sh"),
    env=custom_env,
    ...
)

#!/bin/bash
echo "arg1: $1"
echo "arg2: $2"
echo "env arg: ${foo}"

note that /bin/sh and /bin/bash are different, but practically bash has some extra features which are convenient and it won't really matter here

Bash file:

#!/bin/sh

echo "$1"

Python file:

import subprocess

path_to_bash_file = 'path_to_bash_file'

arg_1 = 10

subprocess.check_call([path_to_bash_file, str(arg_1)])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM