How to pass the Python variable to c shell script

余生颓废 提交于 2019-12-13 02:58:39

问题


I am using Centos 7.0 and PyDEv in Eclipse. I am trying to pass the variable in Python into c shell script. But I am getting error:

This is my Python script named raw2waveconvert.py

num = 10
print(num)
import subprocess
subprocess.call(["csh", "./test1.csh"])

Output/Error when I run the Python script:

10

num: Undefined variable.

The file test1.csh contains:

#!/bin/csh
set nvar=`/home/nishant/workspace/codec_implement/src/NTTool/raw2waveconvert.py $num` 
echo $nvar

回答1:


Okey, so apparently it's not so easy to find a nice and clear duplicate. This is how it's usually done. You either pass the value as an argument to the script, or via an environmental variable.

The following example shows both ways in action. Of course you can drop whatever you don't like.

import subprocess
import shlex

var = "test"
env_var = "test2"
script = "./var.sh"

#prepare a command (append variable to the scriptname)
command = "{} {}".format(script, var)
#prepare environment variables
environment = {"test_var" : env_var}

#Note: shlex.split splits a textual command into a list suited for subprocess.call
subprocess.call( shlex.split(command), env = environment )

This is corresponding bash script, but from what I've read addressing command line variables is the same, so it should work for both bash and csh set as default shells.

var.sh:

#!/bin/sh

echo "I was called with a command line argument '$1'"
echo "Value of enviormental variable test_var is '$test_var'"

Test:

luk32$ python3 subproc.py 
I was called with a command line argument 'test'
Value of enviormental variable test_var is 'test2'

Please note that the python interpreter needs to have appropriate access to the called script. In this case var.sh needs to be executable for the user luk32. Otherwise, you will get Permission denied error.

I also urge to read docs on subprocess. Many other materials use shell=True, I won't discuss it, but I dislike and discourage it. The presented examples should work and be safe.




回答2:


subprocess.call(..., env=os.environ + {'num': num})



回答3:


The only way to do what you want here is to export/pass the variable value through the shell environment. Which requires using the env={} dictionary argument.

But it is more likely that what you should do is pass arguments to your script instead of assuming pre-existing variables. Then you would stick num in the array argument to subprocess.call (probably better to use check_call unless you know the script is supposed to fail) and then use $1/etc. as normal.



来源:https://stackoverflow.com/questions/26366418/how-to-pass-the-python-variable-to-c-shell-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!