Python Error: print subprocess.check_output - invalid syntax - python

Working on a CasperJS tutorial and I'm getting an error with my syntax. Using Python 3.5.1.
File: scrape.py
import os
import subprocess
APP_ROOT = os.path.dirname(os.path.realpath(__file__))
CASPER = '/projects/casperjs/bin/casperjs'
SCRIPT = os.path.join(APP_ROOT, 'test.js')
params = CASPER + ' ' + SCRIPT
print subprocess.check_output(params, shell=True)
Error:
File "scrape.py", line 10
print subprocess.check_output(params, shell=True)
^
SyntaxError: invalid syntax
YouTube Video tutorial: Learning to Scrape...

print subprocess.check_output(params, shell=True) is Python 2 syntax. print is a keyword in Python 2 and a function in Python 3. For the latter, you need to write:
print(subprocess.check_output(params, shell=True))

Related

Run Powershell command in Python (SyntaxError: invalid syntax)

I'm trying to execute a code on the system that downloads a file from direct link to %appdata% dir on Windows.
My code:
def downloadfile():
mycommand = "powershell -command "$cli = New-Object System.Net.WebClient;$cli.Headers['User-Agent'] = {};$cli.DownloadFile('https://drive.google.com/uc?export=download&id=19LJ6Otr9p_stY5MLeEfRnA-jD8xXvK3m', '%appdata%\putty.exe')""
down = subprocess.call(mycommand)
downloadfile()
But I get this error:
File "searchmailfolder.py", line 4
mycommand = "powershell -command "$cli = New-Object System.Net.WebClient;$cli.Headers['User-Agent'] = 'myUserAgentString';$cli.DownloadFile('https://drive.google.com/uc?export=download&id=19LJ6Otr9p_stY5MLeEfRnA-jD8xXvK3m', '%appdata%\putty.exe')""
^
SyntaxError: invalid syntax
Hope this helps.Import subprocess and sys. And then try something like this
"command = subprocess.Popen(["powershell.exe","user_command.ps1"],stdout=sys.stdout)
command.communicate()"
Try putting your code into the .ps1 file

passing argument from python to subprocess.popen

I have this code:
from subprocess import Popen
link="abc"
theproc = Popen([sys.executable, "p1.py",link])
I want to send the variable "link" to p1.py,
and p1.py will print it.
something like this. here is p1.py:
print "in p1.py link is "+ link
How can I do that?
I'm assuming python refers to Python 2.x on your system.
Retrieve the command line argument in p1.py using sys.argv:
import sys
if not len(sys.argv) > 1:
print "Expecting link argument."
else:
print "in p1.py link is " + sys.argv[1]
There's a function subprocess.check_output that is easier to use if you only want to call a program and retrieve its output:
from subprocess import check_output
output = check_output(["python", "p1.py", "SOME_URL"])
print "p1.py returned the following output:\n'{}'".format(output)
Example output:
$ python call_p1.py
p1.py returned the following output:
'in p1.py link is SOME_URL
'
You have to parse the command line arguments in your p1.py to get it in a variable:
import sys
try:
link = sys.argv[1]
except IndexError:
print 'argument missing'
sys.exit(1)

python os.system from input nor working

#!/usr/bin/env python
import os
import subprocess
mail=raw_input("")
os.system("mail" + mail + "<<<test")
When I run this program I`ve got error :sh: 1: Syntax error: redirection unexpected.
The script must send mail using mailutilis
Don't use os.system. Replace it with subprocess.Popen:
address = raw_input()
with open('test') as text:
subprocess.Popen(["mail", address], stdin=text).wait()

'{' is not recognized as internal or external command [duplicate]

This question already has an answer here:
'{' is not recognized as an internal or external command, operable program or batch file
(1 answer)
Closed 2 years ago.
I'm new on Python and following the Google Developers tutorial. I got an error --> '{' is not recognized as internal or external command when running 'python code.py .' with the code below. I believe my PATH variable is set correctly for python as I can run other python codes without problem. Can anybody give me some suggestions?
import os
import sys
import commands
def List(dir):
cmd = 'dir' + dir
print 'about to do this:', cmd
(status, output) = commands.getstatusoutput(cmd)
if status:
sys.stderr.write('there was an error:'+ output)
sys.exit(1)
print output
def main():
List(sys.argv[1])
if __name__ == "__main__":
main()
The commands module doesn't work on Windows – it's Unix-only. Additionally, it's deprecated since version 2.6, and it has been removed in Python 3, so you should use the subprocess module instead. Replace these lines:
import commands
(status, output) = commands.getstatusoutput(cmd)
With something like this:
import subprocess
output = subprocess.check_output(['dir', dir])
Also following the Google Python course..
My commands.getstatusoutput() replacement looks like this:
import subprocess
try:
output = subprocess.check_output(['dir', dir])
except subprocess.CalledProcessError as e:
print "Command error: " + e.output
print "Command output: " + output
sys.exit(e.returncode)

Why is `subprocess.call` not invoking the command

I'm trying to run a .wav file through ffmpeg using the subprocess.call(shell=True) in the following code and it doesn't seem to run. I know this because the output_file isn't created and I'm getting an exception in the open() method.
What am I doing wrong?
try:
import pocketsphinx
except:
import pocketsphinx as ps
import sphinxbase
import subprocess
import os
hmmd = "../../Pocketsphinx_Files/en-us-8khz"
lmdir = "../../Pocketsphinx_Files/cmusphinx-5.0-en-us.lm"
dictp = "../../Pocketsphinx_Files/cmu07a.dic"
output_filename = "../../temp/ps_output.wav"
def recognize(filename="../../temp/temp_output.wav"):
command = "ffmpeg -i "+filename+" -ac 1 -ab 16 -ar 16000 "+output_filename
subprocess.call(command,shell=True)
wavFile = open(output_filename,"rb")
speechRec = ps.Decoder(hmm = hmmd, lm = lmdir, dict = dictp)
wavFile.seek(44)
speechRec.decode_raw(wavFile)
result = speechRec.get_hyp()
#os.remove(filename)
#os.remove(output_filename)
return result
if __name__=="__main__":
print(recognize())
edit: I've got ffmpeg installed.
Furthermore, when I run the subprocess.call() command from the python interpreter it seems to work. This is why I'm stumped.
I would recommend that you try using subprocess.check_call() or check_output instead of simply call. They will raise an exception if your program fails to execute correctly, instead of leaving you wondering why no output was generated.
I'm going to guess that you may somehow be having path issues with your executable in a Python environment
Try using this function with 'ffmpeg':
def is_exe(prog):
for path in os.environ["PATH"].split(os.pathsep):
if os.path.isfile(os.path.join(path, prog)):
if os.access(os.path.join(path, prog), os.X_OK):
return os.path.join(path, prog)
else:
print "Program '%s' found in '%s', but lacks executable permissions." % (prog, path)
return False
If it returns False, you're having problems with Python running ffmpeg, otherwise it's ffmpeg which is having problems making sense of your arguments.

Categories

Resources