简体   繁体   English

使用 tcl 脚本调用 python function 和 arguments

[英]calling python function with arguments using tcl script

I have a python script (sample.py) that has a function with 3 arguments.我有一个 python 脚本 (sample.py),它有一个 function 和 3 个 arguments。 where 1st two arguments are in hex and 3rd is the string.其中第一个两个 arguments 是十六进制,第三个是字符串。

def sampleFun(gen_lane,sw_state,test_name):`
    
    ### code segment 

    output = "some string"
    return output

I have to use tcl script to call this function sampleFun present in sample.py.我必须使用 tcl 脚本来调用 sample.py 中存在的这个 function sampleFun。

How to do that?怎么做? I have tried this tcl command:我试过这个 tcl 命令:

proc call_python { } {
    set gen_lane 0x10500000
    set sw_state 0x0000000B
    set test_case "linkup"
    set result [exec python -c "import sample; print sample.sampleFun($gen_lane,$sw_state,$test_case)"]
    puts $result

}

But I am getting the error that the name "linkup" is not defined.但是我收到了未定义名称“linkup”的错误。

So, how to pass a string argument to the python function from tcl?那么,如何将字符串参数从 tcl 传递给 python function?

You need to quote it for Python.您需要为 Python 报价。

For an almost-arbitrary value like that, you'd try this:对于这样的几乎任意值,您可以尝试以下操作:

set result [exec python -c "import sample; print sample.print_file($gen_lane,$sw_state,r'''$test_case''')"]

This uses the fact that ''' -quoted strings in Python can contain newlines and single ' characters, and r strings can contain backslashes.这使用了这样一个事实,即 Python 中'''引用的字符串可以包含换行符和单个'字符,并且r字符串可以包含反斜杠。 The cases remaining that could possibly cause problems are rare.剩下的可能导致问题的案例很少见。

You are aware that your example Python code said sampleFun but your test code said sample.print_file ?您知道您的示例 Python 代码说sampleFun但您的测试代码说sample.print_file I assume you can fix that up…我想你可以解决这个问题……

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

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