簡體   English   中英

從 python 文件執行 shell 腳本時,如何將值存儲到 shell 腳本中的文件?

[英]How to store values to a file in shell script when executing the shell script from python file?

我需要從 python 文件中觸發 shell 腳本。 shell 腳本需要執行一些命令並將數據存儲在另一個文件中。

問題:我能夠從 python 觸發 shell 腳本,但是在 shell 腳本中執行的命令給出了空響應並在相應的腳本中存儲“Cg==”。

Shell 腳本:randscript.sh

生成隨機值並將其存儲到 newfile。

echo Pass = $(echo $RANDOM | base64 | head -c 20)>>newfile

Python:randfile.py

執行 python 文件觸發 shell 腳本。

import os
import subprocess
def rand_func():
  try:
    path = '/home/ubuntu/execution'
    os.chdir(path)
    script_exec = subprocess.call(['sh','./randscript.sh'])
    print(script_exec)
    return True
  except Exception as err:
    print("Exception")
    return False
func_exec = rand_func()

注意:當手動執行命令時,它會返回預期值(給出隨機值)。 但是通過 python 腳本,它返回“Cg==”(這是一個換行符)。 誰能幫我理解這一點?

除非您使用的是 3.5 之前的 Python 版本,否則您可以調整此版本:

import subprocess
import os

os.chdir('/home/ubuntu/execution')

r = subprocess.run(['/bin/sh', './randscript.sh'], capture_output=True)
print(r.stdout.decode())

我假設您的 shell 腳本將相關 output 發送到標准 output ZF7B44ZCFAFD5C5222EB73D

自發布此答案以來,對該問題進行了編輯。 該腳本不會向標准 output stream 發出任何內容。 因此,我的回答是行不通的。 通過添加:

cat newfile

...到腳本的結尾,這將起作用。

另一個(更好的)選擇是:

echo Pass = $(echo $RANDOM | base64 | head -c 20) | tee -a newfile

暫無
暫無

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

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