ilovecomputer
ilovecomputer

Reputation: 4708

Run shell script in python to play audio file in OS X

I'm trying to run some zsh command in Python and I have a variable to input.I'm not familiar with zsh so I tried to handle it as in Applescript but failed.

wordToRead = getClipboardData()

p = subprocess.Popen(
        ['/usr/bin/zsh', '-'] + [wordToRead], 
        stdout=subprocess.PIPE, stderr=subprocess.PIPE,
        stdin=subprocess.PIPE)

scpt = '''
cd $TMPDIR
curl -o wordToRead 'http://dict.youdao.com/dictvoice?audio=wordToRead'
afplay wordToRead
rm wordToRead
'''

p.communicate(scpt)

Actually I even don't know what the zsh code do exactly.However,it will play a audio of wordToRead as result.

how to fix it?

Upvotes: 3

Views: 488

Answers (1)

OneCricketeer
OneCricketeer

Reputation: 191738

Like I said, zsh isn't necessary, the default for the subprocess command on Unix systems is /bin/sh, which can run the script just fine.

import subprocess

wordToRead = getClipboardData()

scpt = '''
cd /tmp
curl -s -o wordToRead 'http://dict.youdao.com/dictvoice?audio={}'
afplay wordToRead
rm wordToRead
'''.format(wordToRead)

p = subprocess.call(scpt, shell=True)

I even don't know what the zsh code do exactly

It is called a shell script, it is not "zsh code".

  1. Goes into the /tmp folder

    cd /tmp
    
  2. Downloads an audio file using the string you specify

    curl -s -o wordToRead 'http://dict.youdao.com/dictvoice?audio={}'
    
  3. Uses the afplay command to open that audio file

    afplay wordToRead
    
  4. Removes the downloaded file

    rm wordToRead
    

Upvotes: 1

Related Questions