如何将Python变量传递给C Shell脚本
我在Eclipse中使用Centos 7.0和PyDEv。我试图将Python中的变量传递到C Shell脚本中。但是我遇到了错误:
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:
这是我的Python脚本,名为raw2waveconvert.py
This is my Python script named raw2waveconvert.py
num = 10
print(num)
import subprocess
subprocess.call(["csh", "./test1.csh"])
运行Python脚本时的输出/错误:
Output/Error when I run the Python script:
10
num: Undefined variable.
文件test1.csh包含:
The file test1.csh contains:
#!/bin/csh
set nvar=`/home/nishant/workspace/codec_implement/src/NTTool/raw2waveconvert.py $num`
echo $nvar
Okey,因此显然很难找到一个好,清楚的重复。通常是这样的。您可以将值作为参数传递给脚本,也可以通过环境变量传递。
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 )
这是相应的bash脚本,但是从我读到的寻址命令行变量来看,它们是相同的,因此它对于两个 bash $ c都应适用$ c>和
csh
设置为默认外壳。
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'"
T est:
luk32$ python3 subproc.py
I was called with a command line argument 'test'
Value of enviormental variable test_var is 'test2'
请注意,python解释器需要适当的访问权限到被调用的脚本。在这种情况下, var.sh
必须对用户 luk32
可执行。否则,您会收到权限被拒绝
错误。
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.
我也希望阅读 子过程
。许多其他材料使用 shell = True
,虽然我不会讨论,但我不喜欢并不鼓励使用。给出的示例应该有效并且安全。
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.