【问题标题】:How to get the variable of loop from Shell script to retrieve inside python script如何从 Shell 脚本中获取循环变量以在 python 脚本中检索
【发布时间】:2015-11-17 00:28:17
【问题描述】:

对不起,我是 python 新手,我只有基本的 Shell 脚本/sh。我有两个问题。 1) 如何从 bash 中获取循环变量以在 python 脚本中检索? 2) 如何将多个文件的最大键值保存到同一个字典中?

上述问题是相关的。 解释: 主脚本在 Shell 脚本中,他们将在其中循环一些 Shell 命令,然后为许多 K 运行 Python 脚本。

例如:

#!/bin/sh

for a in K*
do
 echo $a
   # Loop to call the file.
   for i in 1 2 3 4 5
   do
      # Cut the row and column
      grep -v '^#' $a/result*.txt | tr -s ' ' | cut -d ' ' -f 6 | cat > pos.txt
   done
chmod a+wx pie1.py
./pie1.py $a/pos.txt $a/neg.txt

chmod a+wx max.py
./max.py $a/output1.py

所以在 max.py 中我制作了一个字典,它将保存键和最大值。

#!/usr/bin/env python

#import pickle
from output1 import *
import subprocess

dicoMax = {}
# The Flist read from output1 that save all the Fscore for one File
dicoMax['K*']=max(Flist)
print(dicoMax)

我想从 Shell 脚本中检索 K* 或 变量作为 max.py(python 脚本)中字典的键,最后将 K* 的所有键和最大值保存在一本字典。

Tq。

【问题讨论】:

  • 如果您将 shell 脚本和 python 脚本的功能组合成 1 个脚本(可能是 python),这可能会更容易。
  • 顺便说一句,源文件上的chmod a+w 是一个可怕的想法:这意味着您系统上的任何用户,包括像nobody 这样的系统用户,用于运行完全不受信任的守护进程代码(即在网络上与潜在的敌对用户交互)可以修改您的源文件。
  • 也就是说——您已经"$a/pos.txt""$a/neg.txt" 作为参数传递,所以,好吧,您知道如何从shell 传递参数(尽管Python您提供的代码不会检索它们)。为什么你不能以完全相同的方式也传递"$a"本身?
  • @CharlesDuffy,我会修改我的源代码。我是python和shell的新手,所以我确实知道"$a/pos.txt"作为参数传递,我只是想如果我们想使用我们需要首先声明的文件,我已经尝试过了。它成功传递了参数 tq。
  • 顺便说一句——还可以考虑通过shellcheck.net 运行您的代码,并解决它引发的问题。

标签: python linux shell dictionary


【解决方案1】:

有两种方法 - 您可以将其作为命令行参数传递(这将是最好的方法),或者您可以将其插入环境变量(这不太清楚)

阅读此dive into python tutorial 将是一个好的开始。

【讨论】:

  • 一个好的答案足够完整,无需外部链接就可以独立存在(并不是说拥有链接是不好的——恰恰相反——但答案应该仍然足够好,在没有它们的情况下会有所帮助) .我至少建议展示如何将 shell 变量导出到子进程的环境(使用 export 命令或使用单行命令行范围语法)。
【解决方案2】:

对于问题 1 和 2:

#!/bin/sh

chmod a+wx pie1.py
for a in K*
do
 echo $a
   # Loop to call the file.
   for i in 1 2 3 4 5
   do
      # Cut the row and column
      grep -v '^#' $a/result*.txt | tr -s ' ' | cut -d ' ' -f 6 | cat > pos.txt
   done

./pie1.py $a/pos.txt $a/neg.txt
### passing the arguments or value through "$a"
./max.py "$a" $a/output1.py
done

所以在python中

#!/usr/bin/env python

from output1 import *
from maxList import *
import sys  

dicoMax = {}
var = sys.argv[1] ###important
print var  
### Flist is the list of the Fscore that save in the output1 
### var is the key passing by Shell script
dicoMax[var]=max(Flist)
print(dicoMax)
### mList is the dictionary that save in the maxList file (mList must   
### be declared first) 
### it will update new key:value pair for new loop of Shell script
dicoMax.update(mList)
### Save the updated mList in maxList
a=open('maxList.py', 'w')
a.write("mList=%s\n" % dicoMax)
a.close()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-02
    • 1970-01-01
    • 2013-10-26
    • 2013-06-15
    • 2022-12-04
    • 2016-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多