如何将 Bash 变量传递给 Python? [英] How to pass a Bash variable to 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 脚本:
#!/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]
谢谢
推荐答案
导出的 bash 变量实际上是环境变量.您可以通过 os.environ 对象使用类似字典的界面来获取它们.请注意,Bash 中有两种类型的变量:当前进程本地的变量和子进程继承的变量.您的 Python 脚本是一个子进程,因此您需要确保export
您希望子进程访问的变量.
Exported 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.
要回答您的原始问题,您需要先导出变量,然后使用 os.environ
从 python 脚本中访问它.
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]
或者,您可以将变量作为命令行参数传递,这就是您的代码现在正在执行的操作.在这种情况下,您必须查看 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]
这篇关于如何将 Bash 变量传递给 Python?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!