[英]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.我在 spyder3 上写了一个脚本,它通过函数“subprocess.call”调用一个 bash 文件并传递(或应该这样做)一个变量。 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.
问题是,不熟悉 bash 编码,我不知道如何导入/读取此变量和(例如)打印或回显它。 Here are my lines of code on spyder:
这是我在 spyder 上的代码行:
variable='test'
subprocess.call(['./path/bash_file.sh',variable])
And on the bash file:在 bash 文件上:
#!/bin/sh
echo variable
But obviously something is missing, in the bash file at least(?).但显然缺少某些东西,至少在 bash 文件中(?)。
either pass the variables to the bash script as arguments or environmental vars将变量作为参数或环境变量传递给 bash 脚本
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请注意
/bin/sh
和/bin/bash
是不同的,但实际上bash
有一些额外的功能,这些功能很方便,在这里并不重要
Bash file: bash文件:
#!/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)])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.