簡體   English   中英

有沒有辦法在由Python腳本創建的內存中保存一大串字符串,並將其提供給當前的bash shell?

[英]Is there a way to hold a big list of strings in memory created from a Python script, and made available to the current bash shell?

想象一下,我在Python程序中列出了很多文件路徑,然后想在終端中使用它。

我可以將其存儲到文件中。

我可以將其通過管道傳遞到Python程序之外,以便bash可以讀取它。

但是是否可以只是設置某種變量,以使當前shell(運行腳本的那個shell)作為普通bash變量訪問輸出?

您可以設置環境變量。

但是,要使當前的shell能夠訪問命中,您可能必須使用一些技巧:

在您的python腳本中,創建一個臨時.sh文件,該文件將使用export yourname=yourlist設置環境變量,然后運行並刪除它。


另一種方法是使用例如python socket模塊的Unix域套接字 ,然后使用socatnetcat在您的外殼中讀取它,或使用python的mmap模塊。

  1. 創建一個python程序以將文件打印到stdout
  2. 使用反引號執行python腳本以將腳本的輸出存儲在bash變量中

請注意,使用“ $ var”訪問bash變量的區別在於保留換行符,而使用普通的$ var則將換行符更改為空格。

paddy$ echo $SHELL
/bin/bash
paddy$ unset frompython 
paddy$ cat alltxt.py 
from glob import glob
print("\n".join(glob("*.txt")))
paddy$ python alltxt.py 
entry3.txt
entry2.txt
test_in2.txt
infile.txt
test_in.txt
entry.txt
entry1.txt
testfile.txt
paddy$ frompython=`python alltxt.py`
paddy$ echo $frompython
entry3.txt entry2.txt test_in2.txt infile.txt test_in.txt entry.txt entry1.txt testfile.txt
paddy$ echo "$frompython"
entry3.txt
entry2.txt
test_in2.txt
infile.txt
test_in.txt
entry.txt
entry1.txt
testfile.txt
paddy$ 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM