繁体   English   中英

如何通过python执行shell脚本

[英]How to execute a shell script through python

我有一个脚本说 abc.sh,其中包含带有标志的命令列表。 例子

//abc.sh
echo $FLAG_name
cp   $FLAG_file1   $FLAG_file2
echo 'file copied'

我想通过python代码执行这个脚本。

//xyz.py

name = 'FUnCOder'
filename1  = 'aaa.txt'
filename2 = 'bbb.txt'

subprocess.call([abc.sh, name, filename1, filname2], stdout=PIPE, stderr=PIPE, shell=True)

此调用不起作用。

其他选项是什么?

此外,shell 脚本文件位于其他目录中。 我希望输出进入日志。

通常你想使用Popen因为你之后有过程控制。 尝试:

process = subprocess.Popen(['abc.sh', name, filename1, filname2], stdout=PIPE, stderr=PIPE)
process.wait() # Wait for process to complete.

# iterate on the stdout line by line
for line in process.stdout.readlines():
    print(line)

试试这个:

//xyz.py

name = 'FUnCOder'
filename1  = 'aaa.txt'
filename2 = 'bbb.txt'

process = subprocess.Popen(['abc.sh', name, filename1, filname2], stdout=PIPE)
process.wait()

请注意,'abc.sh' 用引号引起来,因为它不是变量名,而是您正在调用的命令。

一般来说,我也建议使用shell=False ,但在某些情况下有必要使用shell=True

要将输出放入文件中,请尝试:

with open("logfile.log") as file:
    file.writelines(process.stdout)

我知道这是一个老问题,如果您使用的是 Python 3.5 及更高版本,下面是方法。

import subprocess
process = subprocess.run('script.sh', shell=True, check=True, timeout=10) 

参考: https : //docs.python.org/3.5/library/subprocess.html#subprocess.run

我在 macOS 上运行我使用的 shell 脚本:

process = subprocess.Popen([abc.sh, name, filename1, filname2], shell=True)

暂无
暂无

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

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