使用python执行shell脚本 并动态传参

方法一
脚本(2.sh):

#!/usr/bin/env sh
root_passwd=$1
echo $root_passwd

function main()
{
    
    
  echo "hello shell"
}

main

python程序(sus.py):

import subprocess
p = subprocess.Popen(args=['./2.sh','888'],shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
cc = p.stdout.read().strip()
dd = bytes.decode(cc)
print(dd)
print(type(dd))

打印:

[root@localhost demo01]# python3 sus.py 
888
hello shell
<class 'str'>

Popen用法源码解释

class Popen(object):

    _child_created = False  # Set here since __del__ checks it

    def __init__(self, args, bufsize=-1, executable=None,
                 stdin=None, stdout=None, stderr=None,
                 preexec_fn=None, close_fds=_PLATFORM_DEFAULT_CLOSE_FDS,
                 shell=False, cwd=None, env=None, universal_newlines=False,
                 startupinfo=None, creationflags=0,
                 restore_signals=True, start_new_session=False,
                 pass_fds=()):

参数是:

args 应该是一个字符串,或一系列程序参数。要执行的程序通常是args序列或字符串中的第一项,但可以使用可执行参数进行显式设置。

在UNIX上,与shell=False(默认):在这种情况下,POPEN 类使用os.execvp()来执行子程序。 args通常应该是一个序列。一个字符串将被视为一个字符串作为唯一项目(要执行的程序)的序列。

在UNIX上,使用shell = True:如果args是一个字符串,则它指定要通过shell执行的命令字符串。如果args是一个序列,则第一个项目指定命令字符串,并且任何其他项目将被视为附加的shell参数。
脚本拿不到参数和shell参数值和args参数值有关
方法二:
脚本(2.sh):

#!/usr/bin/env sh
root_passwd=$1

function main()
{
    
    
  echo $root_passwd
  return 1
}

main

python程序(sus.py):

import subprocess
path = './2.sh'
pwd = 'mima'
cmd = path + ' ' + pwd
a,b=subprocess.getstatusoutput(cmd)
print(a)
print(b)

打印:

[root@localhost demo01]# python3 sus.py 
1
mima

getstatusoutput用法源码解释

getstatusoutput(cmd):
    Return (status, output) of executing cmd in a shell.

    Execute the string 'cmd' in a shell with 'check_output' and
    return a 2-tuple (status, output). Universal newlines mode is used,
    meaning that the result with be decoded to a string.

    A trailing newline is stripped from the output.
    The exit status for the command can be interpreted
    according to the rules for the function 'wait'.  Example:

    >>> subprocess.getstatusoutput('ls /bin/ls')
    (0, '/bin/ls')
    >>> subprocess.getstatusoutput('cat /bin/junk')
    (256, 'cat: /bin/junk: No such file or directory')
    >>> subprocess.getstatusoutput('/bin/junk')
    (256, 'sh: /bin/junk: not found')

猜你喜欢

转载自blog.csdn.net/qq_34663267/article/details/112600433
今日推荐