简体   繁体   中英

Easily creating a bash script in python

I'm looking to write some tests that will create and execute a bash script. Bash itself has a nice way to do this:

 % cat > run.sh << EOF
 > echo "I ran this"
 > EOF
 % . run.sh
 I ran this

In Python I can do this:

 with open ('run.sh', 'w') as rsh:
    rsh.write('echo "I ran this"\n')
 -- etc ---

This is fine for a short script in Python, but I'm wondering if there is some technique I don't know about that let's me do something like what I can do in bash.

You can do this

#! /usr/bin/env python

with open ('run.sh', 'w') as rsh:
    rsh.write('''\
#! /bin/bash
echo "I ran this"
echo "more lines"
''')

You Can Use writelines here:

with open ('run.sh', 'w') as rsh:
    rsh.writelines('echo "I ran this"\n')

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