繁体   English   中英

如何从带参数构建的 3.x 运行 python 2.x 函数? PSS/E

[英]How can i run a python 2.x function from a 3.x built with arguments? PSS/E

嗨,我有一个函数,它看起来只能在 2.x (2.7) 系统中运行。 但是我程序的其余部分是用 python 3.4 编写的

文件a.py (2.7 版)是一个脚本,我可以通过调用脚本在 2.7 中运行:

import psspy    
openPath='busSystem.raw'
saveToPath='busSystem_out.raw'

#Open a case file
psspy.read(0,openPath)
do some calculation...

#Save to another case file
psspy.rawd_2(0,1,[1,1,1,0,0,0,0],0,saveToPath)

然后在b.py 中从 python 3.4 调用以下代码工作

import os
os.system('c:\python27\python a.py')

但是后来我想将a.py 中的脚本更改为带有 kwargs 的函数,例如:

def run(openPath='busSystem.raw',saveToPath='busSystem_out.raw')
    #Open a case file
    psspy.read(0,openPath)
    do some calculation...

    #Save to another case file
    psspy.rawd_2(0,1,[1,1,1,0,0,0,0],0,saveToPath)
    do something more...

所以我想做类似的事情

import os
in = 'busSystem.raw'
out = 'busSystem_out.raw'
os.system('c:\python27\python a.py run(in, out)')
# Or
os.system('c:\python27\python a.py run(openPath=in,saveToPath=out)')

所以问题是:

  • 如何将参数发送到另一个脚本的函数?
  • 我可以同时使用 args 和 kwargs 吗?

我知道我是否可以使用 python 3.4 运行脚本,我可以将函数导入为

from a import run
run(in,out)

我对此的解决方案是将整个 python 脚本读取为字符串,使用 str.replace('busSystem.raw',in) 和 str.replace(''busSystem_out.raw',out) 并将其保存为a_new .py并按照前面提到的方式运行它。

a.py 中的脚本需要在python 2.7 版本中,因为它与Siemens PSS/E 33 交互,后者仅通过py2.7 进行通信。

函数调用只能在单个进程中工作,而且通常只能在一种语言中工作。 所以你有一个可以不带参数运行的脚本。 现在您希望此脚本处理命令行参数。 这实际上与函数调用和关键字参数无关。

您应该阅读 Python 文档中的Argparse 教程 它介绍了命令行参数的概念,因为您似乎不熟悉它,然后展示了一些使用内置argparse模块来完成解析参数的困难部分的示例。

然后您应该阅读有关subprocess模块的信息。 它比os.system()更适合你。

或者,您可以更新脚本,使其在 Python 3 中正常工作。这就是我要开始的。

这是一些未经测试的示例代码。

在您现有的脚本a.py

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('openPath')
parser.add_argument('saveToPath')

args = parser.parse_args()

openPath=args.openPath
saveToPath=args.saveToPath

# ... the rest of the existing script

在您的其他程序中:

import subprocess
in_ = 'busSystem.raw'
out = 'busSystem_out.raw'
subprocess.call([r'c:\python27\python', in, out])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM