【问题标题】:Running Linux commands using python script使用 python 脚本运行 Linux 命令
【发布时间】:2020-09-03 10:59:09
【问题描述】:

我正在编写一个执行基本 shell 命令的 python 脚本。喜欢-

  • 从服务器签出一个 shell 文件 - ct co -nc file_name
  • 在 shell 终端中设置环境变量 - setenv 变量值
  • 将文件签入服务器 - ct ci -nc file_name。

基本上我想知道如何通过python脚本执行基本命令。 也有人可以帮助我了解是否有任何方法可以通过 python 脚本获取具有上述基本 shell 命令的 .cshrc (source file_name.cshrc) 文件?

以下是我遵循的示例代码-

import sys
import subprocess
file_name = sys.argv[0]
print ("file name is ==>", file_name)
cmd = ['ct co -nc file_name']
time = subprocess.Popen (cmd, shell=True)
output,err = time.communicate()
print(output)

错误:

('given file name is ==>', 'script_test_sys.py')
/bin/sh: ct: command not found
None

【问题讨论】:

  • ['ct co -nc file_name'] 中的所有参数都应该像['ct', 'co', '-nc', 'file_name'] 这样用逗号分隔,或者直接将字符串作为命令传递cmd = 'ct co -nc file_name'
  • 避免使用shell=True,除非你绝对必须......它会带来各种各样的问题,而且大多数时候不需要它。
  • 使用 ct 命令的完整路径

标签: python linux shell


【解决方案1】:

['ct co -nc file_name'] 中的所有参数都应该像这样用逗号分隔

cmd = ['ct', 'co', '-nc', 'file_name'] 

或者直接将字符串作为命令传递

cmd = 'ct co -nc file_name'

【讨论】:

  • 嗨,谢谢您的回复。我已经弄清楚了它的工作方式。 import sys import subprocess cmd = ['cleartool co -nc file_name'] time = subprocess.Popen (cmd, shell=True) output,err = time.communicate() print(output)