【问题标题】:Shell script taking for argument a Python variable以 Python 变量为参数的 Shell 脚本
【发布时间】:2021-08-21 10:40:20
【问题描述】:

我有一个名为“scriptNastran.py”的简单 Python 脚本,它通过子进程函数调用 shell:

import subprocess

subprocess.call(['sh', './launchNastran.sh'])

我的 launchNastran.sh 是:

/appli/nastran -msc20121 TRAM mem=512M buffsize=25601 batch=no    
CHEMIN='/users/develop/tmp/input'
\cp -rf TRAM MODELE ./*f06 ./*f04 ./*log ./*op2 ./*pch $CHEMIN

文件 TRAM 和 MODELE 与 shell 和 Python 脚本位于同一目录中。在 Shell 中可以看到该目录:CHEMIN='/users/develop/tmp/input

但是,Python 脚本中的目录发生了变化,所以我想将 Python 脚本中定义的 arg_directory 作为 shell 的参数传递,类似于:

import subprocess
arg_directory = 'hello world'
subprocess.call(['sh', './launchNastran.sh'])

对于 python 脚本和 shell 类似:

$ scriptNastran.py arg_directory

/appli/nastran -msc20121 TRAM mem=512M buffsize=25601 batch=no    
CHEMIN= arg_directory
\cp -rf TRAM MODELE ./*f06 ./*f04 ./*log ./*op2 ./*pch $CHEMIN

有人知道怎么做吗?

感谢您的帮助:)

【问题讨论】:

  • 您的目标是在 python 中运行launchNastran.sh 或从 python 获取结果然后传递给launchNastran.sh shell 脚本?
  • 我的目标是在 python 中运行 launchNastran.sh

标签: python shell subprocess


【解决方案1】:

您可以将目录作为参数传递:

import subprocess
arg_directory = 'hello world'
subprocess.call(['sh', './launchNastran.sh', arg_directory])

然后在你的 shell 脚本中读取它

/appli/nastran -msc20121 TRAM mem=512M buffsize=25601 batch=no    
CHEMIN="$1"
\cp -rf TRAM MODELE ./*f06 ./*f04 ./*log ./*op2 ./*pch "$CHEMIN"

【讨论】:

  • 简洁优雅!非常感谢
【解决方案2】:

launchNastran.py

def call_shell(CHEMIN_path):
    import subprocess
    ssh_command_string='''
        /appli/nastran -msc20121 TRAM mem=512M buffsize=25601 batch=no    
        CHEMIN={path}
        \cp -rf TRAM MODELE ./*f06 ./*f04 ./*log ./*op2 ./*pch $CHEMIN
    '''.format(path=CHEMIN_path). ## put the path you have in format 
    subprocess.Popen(ssh_command_string, shell=True)
call_shell('/users/develop/tmp/input') ## call the shell script

【讨论】:

    猜你喜欢
    • 2011-10-16
    • 2013-10-19
    • 2020-05-20
    • 1970-01-01
    • 1970-01-01
    • 2010-11-13
    • 2016-01-21
    • 2015-01-21
    • 1970-01-01
    相关资源
    最近更新 更多