Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there any other altrenative to ">" in BASH w/ Python Subprocess

I am trying to print out my outputs into a log file, I am using python with subprocess to do so. But when I use > in code, I am getting error like:

+ klm.py scan /home '>' /home/userA/out/home_03-30-2022_11-07-32.log

2022-03-30 09:09:21,074 ERROR > does not exist

Here is the code I am running:

subprocess.run(['sudo', 'docker', 'run', '-it', '--rm', '-w', '/workdir', '-v', f'{pwd}:/workdir:ro', 'docker-local.abc.xyz.xyz.name.com/klm', 'klm.py', 'scan', f"{pwd}", ">", f'/home/userA/out{directory}_{date_time}.log'])

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Whenever I use the command itself directly into the terminal, command is working working without any error and creating the .log files, I assume this is error coming from subprocess or python side.

> directory variable is a for loop of list elements -> DIRECTORIES = [/home, /root, etc]

> datetime just a string -> date_time 

> pwd is -> pwd = os.getcwd()

> I don't know if it is useful info but I am using Kali Linux for this

>Solution :

I’d like to show a standard output redirection on a simpler command. It prints the date and time to a file. First using shell’s redirection and then without the shell’s help (shell=False is the default)

import subprocess

# with shell redirection
subprocess.run(['date >out1.txt'], shell=True)

# without shell
with open('out2.txt', 'w') as out:
    subprocess.run(['date'], stdout=out)

Note: the documentation asks you to read the Security Considerations before using shell=True.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading