【问题标题】:Py2 - Run Bash Script with Arguments - Store Output in a file in a different directoryPy2 - 使用参数运行 Bash 脚本 - 将输出存储在不同目录的文件中
【发布时间】:2022-01-14 14:43:06
【问题描述】:

我的代码:

for host in hostlist_split:
    path = currentDIR + "/" + scriptRESULTS + runtimeSCRIPT
    if os.path.exists(path):
        print 'Executing Script...'
        subprocess.check_call(['path', 'username', 'password'])
        print(stdout)
        sitesProcessed += 1

脚本从文件中读取主机列表,遍历它们,在该主机上运行另一个脚本,传递运行所需的参数,然后理想地将该下标的输出存储在一个新文件中。

我将以脚本运行所在的主机命名文件并将其存储在以下标命名的目录中。

问题是我在执行此代码时收到消息no such file or directory

  1. 我已验证主机被正确读取并以字符串形式存储在列表中。
  2. 我已验证下标的路径、用户名和密码都按预期存储和提供。

但是当使用check_call 函数时,脚本不会运行,并且不会打印标准输出。

错误:

Traceback (most recent call last):
  File "./pywrapper.py", line 136, in <module>
    subprocess.check_call(['path', 'username', 'password'])
  File "/usr/lib64/python2.7/subprocess.py", line 537, in check_call
    retcode = call(*popenargs, **kwargs)
  File "/usr/lib64/python2.7/subprocess.py", line 524, in call
    return Popen(*popenargs, **kwargs).wait()
  File "/usr/lib64/python2.7/subprocess.py", line 711, in __init__
    errread, errwrite)
  File "/usr/lib64/python2.7/subprocess.py", line 1327, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

【问题讨论】:

  • 快速检查一下:您的第一个样本有一个名为 path 的变量,但您的回溯显示了一个文字字符串 'path'。这些是非常不同的事情。
  • 哈哈,你说得对,我将路径作为字符串而不是变量提供。我确实纠正了它,但现在我得到 [错误 13] 权限被拒绝大声笑 - 并且要清楚我已经运行 chmod 777 * 和 dos2unix
  • 第 1 行是否有适当的 shebang 行,例如 #! /bin/bash 告诉内核要执行什么?
  • 是的,我愿意。这不是这里的问题。

标签: python bash python-2.7


【解决方案1】:

我的脚本没有扩展变量,它只是将它们作为字符串读取。 我刚从 BASH 切换,所以弄清楚如何在不添加空格的情况下将字符串和变量组合在一行中花了我一段时间。

这就是我现在正在运行的..

for host in hostlist_split:
    path = currentDIR + '/' + scriptRESULTS + runtimeSCRIPT

    if os.path.exists(path):
        print 'Executing Script...'
        sshARGS =  ('{}/{} {} {} {} > {}/{}'.format(currentDIR, runtimeSCRIPT, host, username, password, path, host) ) 
        SSH = subprocess.Popen(sshARGS, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out, err = SSH.communicate()
        SSH.wait()
        sitesProcessed += 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-03
    • 2017-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-06
    • 1970-01-01
    相关资源
    最近更新 更多