简体   繁体   中英

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

I need to trigger a shell script from a python file. That shell script needs to execute a few commands and store the data in another file.

Problem : I'm able to trigger the shell script from python but the commands getting executed inside the shell script is giving empty response and storing "Cg==" in respective file.

Shell script: randscript.sh

Generating random value and storing it to newfile.

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

Python: randfile.py

Executing python file to trigger the shell script.

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()

Note: When the command was executed manually, it is returning the expected value (giving random value). But via python script, it is returning "Cg=="(which is a newline character). Could anyone please help me to understand this?

Unless you're using a version of Python prior to 3.5 you could adapt this:

import subprocess
import os

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

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

I assume that your shell script emits the relevant output to the standard output stream.

Since posting this answer there's been an edit to the question. The script does not emit anything to the standard output stream. Therefore, my answer will not work. By adding:

cat newfile

...to the end of the script, this will work.

Another (better) option would be:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM