Home > other >  Perl to python open() command translation
Perl to python open() command translation

Time:11-22

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)

CodePudding user response:

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)

CodePudding user response:

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.

  • Related