【问题标题】:How to execute a shell script through python如何通过python执行shell脚本
【发布时间】:2013-04-17 07:41:59
【问题描述】:

我有一个脚本说 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 脚本文件也位于其他目录中。我希望输出进入日志。

【问题讨论】:

  • 您是否考虑过使用shutls 而不是 bash 脚本。试试shutils.copyfile
  • 在这里使用shell=True 是错误的并且会导致错误。

标签: python shell subprocess popen


【解决方案1】:

试试这个:

//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)

【讨论】:

【解决方案2】:

通常你想使用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)

【讨论】:

  • 我试过了,但在屏幕上没有任何输出...你能解释一下重定向到 PIPE 而不是 STDOUT 吗?
  • 通过重定向到 PIPE,您可以使用 process.stdout.readlines()process.stdout.read() 等读取脚本的标准输出。
  • 我认为这也是唯一的选择,因为他想记录输出。
  • 它有效,但脚本没有接受我传递的任何参数。可能是什么问题?
  • 如果您使用与原始问题相同的脚本,那么您做错了。 Shell 脚本参数以$1 $2 $3 等形式传递。
【解决方案3】:

我知道这是一个老问题,如果您使用 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

【讨论】:

    【解决方案4】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-19
      • 1970-01-01
      • 2014-10-06
      • 2020-05-31
      • 1970-01-01
      • 1970-01-01
      • 2011-06-17
      • 1970-01-01
      相关资源
      最近更新 更多