如何通过一个变量猛砸到Python? [英] How to pass a Bash variable to Python?

查看:159
本文介绍了如何通过一个变量猛砸到Python?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最后,我理解这一点,它的工作原理。

Eventually I understand this and it works.

bash脚本:

#!/bin/bash
#$ -V
#$ -cwd
#$ -o $HOME/sge_jobs_output/$JOB_ID.out -j y
#$ -S /bin/bash
#$ -l mem_free=4G


c=$SGE_TASK_ID
cd /home/xxx/scratch/test/
FILENAME=`head -$c testlist|tail -1`
python testpython.py $FILENAME

python脚本:

python script:

#!/bin/python
import sys,os


path='/home/xxx/scratch/test/'
name1=sys.argv[1]
job_id=os.path.join(path+name1)
f=open(job_id,'r').readlines()
print f[1]

THX

推荐答案

Bash的变量实际上是环境变量。您可以通过一个类似于字典的界面os.environ对象获取它们。请注意,有两种类型的在击变量:那些本地当前进程,和那些由子进程继承。你的Python脚本是一个子进程,所以你需要确保你导出你想要的子进程访问的变量。

Bash variables are actually environment variables. You get at them through the os.environ object with a dictionary-like interface. Note that there are two types of variables in Bash: those local to the current process, and those that are inherited by child processes. Your Python script is a child process, so you need to make sure that you export the variable you want the child process to access.

要回答你原来的问题,您需要首先导出变量,然后使用Python脚本中访问 os.environ

To answer your original question, you need to first export the variable and then access it from within the python script using os.environ.

##!/bin/bash
#$ -V
#$ -cwd
#$ -o $HOME/sge_jobs_output/$JOB_ID.out -j y
#$ -S /bin/bash
#$ -l mem_free=4G

c=$SGE_TASK_ID
cd /home/xxx/scratch/test/
export FILENAME=`head -$c testlist|tail -1`
chmod +X testpython.py
./testpython.py


#!/bin/python
import sys
import os

for arg in sys.argv:  
    print arg  

f=open('/home/xxx/scratch/test/' + os.environ['FILENAME'],'r').readlines()
print f[1]

另外,您也可以通过该变量作为命令行参数,这是你的code现在正在做的。在这种情况下,必须查看 sys.argv中,这是传递给脚本的参数列表。他们在你调用脚本时指定它们的相同顺序出现在 sys.argv中 sys.argv中[0] 始终包含正在运行的程序的名称。后续条目包含其他的参数。 LEN(sys.argv中)表示接到剧本参数的数目。

Alternatively, you may pass the variable as a command line argument, which is what your code is doing now. In that case, you must look in sys.argv, which is the list of arguments passed to your script. They appear in sys.argv in the same order you specified them when invoking the script. sys.argv[0] always contains the name of the program that's running. Subsequent entries contain other arguments. len(sys.argv) indicates the number of arguments the script received.

#!/bin/python
import sys
import os

if len(sys.argv) < 2:
    print 'Usage: ' + sys.argv[0] + ' <filename>'
    sys.exit(1)

print 'This is the name of the python script: ' + sys.argv[0]
print 'This is the 1st argument:              ' + sys.argv[1]

f=open('/home/xxx/scratch/test/' + sys.argv[1],'r').readlines()
print f[1]

这篇关于如何通过一个变量猛砸到Python?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆