简体   繁体   English

在执行Shell脚本时,通过python执行带有参数的Shell脚本始终采用默认值

[英]Executing a shell script with parameters through python always takes the default values when executing the shell script

My python is supposed to execute the /home/file.sh with five parameters as shown below. 我的python应该使用以下五个参数执行/home/file.sh。 However, everytime I execute my python script it ignores the parameters and the shell script executes with default values. 但是,每次执行python脚本时,它都会忽略参数,而shell脚本将使用默认值执行。 I have also tried turning the shell to False but no success. 我也尝试过将shell设置为False,但没有成功。 Any ideas ? 有任何想法吗 ? Thank you in advance! 先感谢您!

var1='-t'
var2='m'
var3='20130105'
var4='-f'
var5='test.txt'

process=subprocess.Popen(['/home/file.sh', str(var1), str(var2), str(var3), str(var4), str(var5)],shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
process.wait()
lists=process.communicate()[0]

I have tried the following but it again use the default parameters 我尝试了以下操作,但再次使用默认参数

process=subprocess.Popen(['/home/file.sh  -t m 20140105 -f test.txt')],shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

Try like so: 尝试这样:

process=subprocess.Popen('/home/file.sh -t m 20140105 -f test.txt', shell=True, ...)

without worrying about passing a list for your command. 无需担心传递命令列表。

Either you use an argument list and set shell=False , eg 您可以使用参数列表并设置shell=False ,例如

process=subprocess.Popen(["./test.sh","a","b","c"], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print process.communicate()[0] 

or you can use a string argument and let the shell parse it by setting shell=True , eg 或者,您可以使用字符串参数,并通过设置shell=True让外壳程序解析它,例如

process=subprocess.Popen("./test.sh a b c", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print process.communicate()[0]

but you can not send a list when using shell=True . 但是使用shell=True时无法发送列表。

Both will output 两者都会输出

0: ./test.sh
1: a
2: b
3: c

if test.sh is an executable file with the following contents: 如果test.sh是具有以下内容的可执行文件:

#!/bin/sh

echo 0: $0
echo 1: $1
echo 2: $2
echo 3: $3

Ususally, I prefer using shell=False to avoid having to escape the argument strings (it's trickier than it should be to get this right). 通常,我更喜欢使用shell=False来避免必须转义参数字符串(这比正确实现它更棘手)。 Using the shell has some advantages though, such as expansion of paths, being able to use shell internals and so on. 但是,使用外壳具有一些优点,例如路径扩展,能够使用外壳内部组件等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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