Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
shell script inside python
#1
Hi,
I am trying to generate a shell script inside the python script and then planning to execute it. I know that this is a very naive way. This snippet works. Is there a better way to handle this?Thanks.

        cmd1 = "git clone repoName" + '\n'
        cmd2 = "cd repoName" + '\n'
        cmd3 = "git checkout version" + '\n'
        fh = open(shell_script, 'w')
        fh.write(cmd1)
        fh.write(cmd2)
        fh.write(cmd3)
        fh.close()
Reply
#2
Well, I was using subprocess for this. Most people use it too so there is probably reason why.

Example: https://stackoverflow.com/questions/5702...rom-python
Reply
#3
One approach can be:

import subprocess
import textwrap
import sys
import tempfile


def make_command(repo_name, branch='master'):
    cmd = """
          git clone {0}
          cd {1}
          git checkout {2}
          """
    parent, sep, directory = repo_name.rpartition('/')
    directory = directory.replace('.git', '')
    return textwrap.dedent(
        cmd.format(repo_name, directory, branch)
        ).strip()


def main():
    if len(sys.argv) != 2:
        print(sys.argv[0], 'git-respository.git [branch]')
        sys.exit(1)
    if len(sys.argv) == 3:
        branch = sys.argv[2]
    else:
        branch = 'master'
    respository = sys.argv[1]
    cmd = make_command(respository, branch)
    with tempfile.TemporaryFile(mode='r+') as tmp:
        tmp.write(cmd)
        tmp.seek(0)
        subprocess.Popen(['/bin/sh'], stdin=tmp)


if __name__ == '__main__':
    main()
Ask, if you don't understand it.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#4
(Sep-04-2018, 09:39 AM)DeaD_EyE Wrote:
import subprocess
....
    with tempfile.TemporaryFile(mode='r+') as tmp:
        tmp.write(cmd)
        tmp.seek(0)
        subprocess.Popen(['/bin/sh'], stdin=tmp)
....
Interesting.

One question - why didn't you just use io.StringIO (or io.ByteIO) as a temp file?
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply
#5
Quote:One question - why didn't you just use io.StringIO (or io.ByteIO) as a temp file?

Yes, a BytesIO or StringIO is better in this case. A real file is not needed.

My first thought was, call the shellscript with /bin/bash or /bin/sh (/bin/dash on Debian).
This needs a real file. Then I saw that the shell accepts input from stdin.

You can replace Line 30 with:
with io.StringIO() as tmp:
Unexpectedly StringIO also has also a context manager.
Don't forget to import io.
The module tempfile is no longer needed and should be removed from imports.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#6
(Sep-04-2018, 02:42 PM)DeaD_EyE Wrote: Unexpectedly StringIO also has also a context manager.

Nothing unexpected about that - file objects and stream objects share common base class, see io module doc

Output:
In [32]: file_obj = open('fb_formatter.py') In [33]: file_obj.__class__, file_obj.__class__.__base__ Out[33]: (_io.TextIOWrapper, _io._TextIOBase) In [34]: stream_obj = io.StringIO('This is a stream') In [35]: stream_obj.__class__, stream_obj.__class__.__base__ Out[35]: (_io.StringIO, _io._TextIOBase)
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply
#7
Thanks everyone. I will take it from here :)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to receive two passed cmdline parameters and access them inside a Python script? pstein 2 349 Feb-17-2024, 12:29 PM
Last Post: deanhystad
  Help creating shell scrip for python file marciokoko 10 1,365 Sep-16-2023, 09:46 PM
Last Post: snippsat
  Is there a *.bat DOS batch script to *.py Python Script converter? pstein 3 3,256 Jun-29-2023, 11:57 AM
Last Post: gologica
  Launch Python IDLE Shell from terminal Pavel_47 5 1,234 Feb-17-2023, 02:53 PM
Last Post: Pavel_47
  batch file for running python scipt in Windows shell MaartenRo 2 1,896 Jan-21-2022, 02:36 PM
Last Post: MaartenRo
  cant use ping, sudo or other commands in remote shell script. throwaway34 7 3,599 May-17-2021, 11:29 AM
Last Post: throwaway34
  How to make a Python program run in a dos shell (cmd) Pedroski55 2 2,322 Nov-09-2020, 10:17 AM
Last Post: DeaD_EyE
Bug Python Shell 3.9.0 - Issue with indentation Earis 17 6,648 Oct-31-2020, 07:00 AM
Last Post: Earis
  How to kill a bash script running as root from a python script? jc_lafleur 4 5,903 Jun-26-2020, 10:50 PM
Last Post: jc_lafleur
  crontab on RHEL7 not calling python script wrapped in shell script benthomson 1 2,296 May-28-2020, 05:27 PM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020