【问题标题】:call linux command with variable argument from python从python调用带有可变参数的linux命令
【发布时间】:2015-12-23 01:34:17
【问题描述】:

我正在尝试从 python2x 执行一个程序。

在终端中,作业将运行为:

mpirun -np 8 ~/WORK/scf Fe_SCF.inp > Fe_SCF.out

其中Fe_SCF.*CWD中的输入和输出。

现在,我正在尝试从 python 脚本运行这一段。从那以后,我将它们定义为变量并尝试调用为:

call(["mpirun -np 8 ~/WORK/scf", scfin,  scfout])

给出错误:

  File "./triolith.py", line 38, in <module>
        call(["mpirun -np 8 ~/WORK/scf", scfin,  scfout])
      File "/usr/lib64/python2.7/subprocess.py", line 522, in call
        return Popen(*popenargs, **kwargs).wait()
      File "/usr/lib64/python2.7/subprocess.py", line 710, in __init__
        errread, errwrite)
      File "/usr/lib64/python2.7/subprocess.py", line 1335, in _execute_child
        raise child_exception
    OSError: [Errno 2] No such file or directory

使用真实文件名也不能解决问题:

 call(["mpirun -np 8 ~/WORK/scf", "Fe_SCF.inp",  "Fe_SCF.out"])

这给出了错误:

File "./triolith.py", line 38, in <module>
    call(["mpirun -np 8 ~/WORK/scf", "Fe_SCF.inp",  "Fe_SCF.out"])
  File "/usr/lib64/python2.7/subprocess.py", line 522, in call
    return Popen(*popenargs, **kwargs).wait()
  File "/usr/lib64/python2.7/subprocess.py", line 710, in __init__
    errread, errwrite)
  File "/usr/lib64/python2.7/subprocess.py", line 1335, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

我已经检查并可以确认,使用 os.system 正在使用“真实”文件名,但不是使用变量名:

 os.system("mpirun -np 8 ~/WORK/scf scfin" )

那么,使用两种方法中的任何一种,我怎样才能以变量名作为输入和输出调用程序呢?

【问题讨论】:

    标签: python command-line command


    【解决方案1】:

    call 需要一个列表,因此您的第一个示例应该是:

    cmd = ['/absolute/path/to/mpirun', '-np', '8', '~WORK/scf', var_1]
    call(cmd, stdout=var_2, stderr=STDOUT)
    

    【讨论】:

    • 嗨...谢谢您的回复。它工作正常,除了 var_2 应该是写入我的输出的文件。但这是将输出写入标准输出。我也试过cmd = [ ...., var_1, "&gt;" , var_2] 也不起作用。
    • hd1,这给了我错误SyntaxError: invalid syntaxstdout=var_2
    • hd1,是的……非常好
    【解决方案2】:

    在您使用 OS 模块的后一个示例中,您应该能够:

    os.system("mpirun -np 8 ~/WORK/scf "+ var_name)
    

    运行你的函数调用。

    对于多个变量,d o:

    os.system("mpirun -np 8 ~WORK/scf " + var_1 + " " + var_2)
    

    【讨论】:

      猜你喜欢
      • 2015-05-18
      • 2012-03-10
      • 2015-01-24
      • 2020-05-04
      • 2019-07-09
      • 1970-01-01
      • 2015-08-09
      • 2011-03-30
      • 2011-12-03
      相关资源
      最近更新 更多