bash 将变量从 python 传递给 shell 脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32085956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pass a variable from python to shell script
提问by The Nightman
I am running a shell script from inside a python script like this:
我正在从这样的 python 脚本中运行一个 shell 脚本:
call(['bash', 'run.sh'])
And I want to pass run.sh
a couple of variables from inside of the python script. It looks like I can just append variables, something like so:
我想run.sh
从 python 脚本内部传递几个变量。看起来我只能附加变量,如下所示:
call(['bash', 'run.sh', 'var1', 'var2'])
and then access them in my shell script with $1 and $2. But I can't get this to work.
然后在我的 shell 脚本中使用 $1 和 $2 访问它们。但我无法让它发挥作用。
采纳答案by mhawke
If call(['bash', 'run.sh'])
is working without arguments, there is no reason why it shouldn't work when additional arguments are passed.
如果call(['bash', 'run.sh'])
在没有参数的情况下工作,则没有理由在传递附加参数时它不应该工作。
You need to substitute the valuesof the variables into the command line arguments, not just pass the namesof the variables as strings as does this:
您需要将变量的值替换为命令行参数,而不仅仅是像这样将变量的名称作为字符串传递:
call(['bash', 'run.sh', 'var1', 'var2'])
Instead, do this:
相反,请执行以下操作:
var1 = '1'
var2 = '2'
call(['bash', 'run.sh', var1, var2])
Now this will work providing that var1
and var2
are strings. If not, you need to convert them to strings:
现在这将起作用,var1
并且var2
是字符串。如果没有,您需要将它们转换为字符串:
var1 = 1
var2 = 2
call(['bash', 'run.sh', str(var1), str(var2)])
Or you can use shlex.split()
:
或者你可以使用shlex.split()
:
cmd = 'bash run.sh {} {}'.format(var1, var2)
call(shlex.split(cmd))
回答by Austin A
There are two built-in python modules you can use for this. One is os
and the other is subprocess
. Even though it looks like you're using subprocess
, I'll show both.
有两个内置的 Python 模块可以用于此目的。一个是os
,另一个是subprocess
。即使看起来您正在使用subprocess
,我也会同时展示两者。
Here's the example bash script that I'm using for this.
这是我为此使用的示例 bash 脚本。
test.sh
测试文件
echo
echo
Using subprocess
使用子流程
>>> import subprocess
>>> subprocess.call(['bash','test.sh','foo','bar'])
foo
bar
This should be working, can you show us the error or output that you're currently getting.
这应该有效,您能否向我们展示您当前获得的错误或输出。
Using os
使用操作系统
>>> import os
>>> os.system('bash test.sh foo bar')
foo
bar
0
Note the exit status that os
prints after each call.
注意os
每次调用后打印的退出状态。
回答by Achayan
use subprocess to call your shell script
使用子进程调用你的 shell 脚本
subprocess.Popen(['run.sh %s %s' % (var1, var2)], shell = True).
subprocess.Popen(['run.sh %s %s' % (var1, var2)], shell = True)。
回答by Denis
import os
def run():
os.system('C:\scrips\mybash.bat')
run()