0

How do I write open(SCRPT, ">$script") or die...; in python?? Im trying to run a script in python to automate a slurm job. For that, I am trying to create and open a file names SCRPT and write a block of code to be read and executed.

Is it SCRPT = open(script) with open(SCRPT)

Shawn
  • 47,241
  • 3
  • 26
  • 60
  • Does this answer your question? [How to exit from Python without traceback?](https://stackoverflow.com/questions/1187970/how-to-exit-from-python-without-traceback) – Marcus Müller Nov 21 '22 at 00:45
  • @MarcusMüller What in the world does that question have to do with this one? – Shawn Nov 21 '22 at 02:16
  • 1
    Tutorial for [open](https://www.tutorialsteacher.com/python/open-method) in python. – Polar Bear Nov 21 '22 at 02:26
  • @Shawn I'm assuming a perl programmer can look up python docs. So, since `open`'s equivalent is also called `open`, what remains is the `or die...` part – Marcus Müller Nov 21 '22 at 07:56

2 Answers2

2

The builtin open is typically used to create a filehandle. open raises IOError if anything goes wrong. The functional equivalent of open(SCRIPT,">$script") or die $error_message would be

import sys
try:
    script = open("script", "w")
except IOError as ioe:
    print(error_message, file=sys.stderr)
    sys.exit(1)
mob
  • 117,087
  • 18
  • 149
  • 283
1

File IO in Python is most commonly done using the with ... as operators and the open function, like so:

script = '/path/to/some/script.sh'
with open(script, 'w') as file:
    file.write(
        '#!/bin/bash\n'
        'echo hello world\n'
    )
os.chmod(script, 0o755)  # optional

Note: You only need to do the os.chmod if you need the new script to be directly executed.

Pi Marillion
  • 4,465
  • 1
  • 19
  • 20