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

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)

Related

Piping personal access token into az devops login for Windows cmd

What specific syntax needs to be changed in the Python script below to enable the personal access token to be sucessfully read into the az devops login command without throwing an error?
CURRENT ERROR:
The error being thrown currently is:
'actual-personal-access-token-goes-here' is not recognized as an internal or external command, operable program or batch file.
CALLING PROGRAM:
The Python program that is being called from windows CMD when the error is thrown is called myScript.py and includes:
import subprocess
import re
ansi_escape = re.compile(r'\x1B\[[0-?]*[ -/]*[#-~]')
azPat = 'actual-personal-access-token-goes-here'
orgServiceURL = 'actual-org-service-url-goes-here'
azdoLoginCmd='az devops login --organization '+orgServiceURL
dblCmd = azPat + " | " + azdoLoginCmd
proc = subprocess.Popen( dblCmd,cwd=None, stdout=subprocess.PIPE, shell=True)
while True:
line = proc.stdout.readline()
if line:
thetext=line.decode('utf-8').rstrip('\r|\n')
decodedline=ansi_escape.sub('', thetext)
print(decodedline)
else:
break
CALL TO INVOKE PROGRAM:
The command typed into windows CMD that calls the above program and throws the above error is:
python3 myScript.py
OFFICIAL DOCUMENTATION:
The official Microsoft documentation is at this link .
The following is what works to resolve the error in the OP:
azdoLoginCmd= "ECHO " + azPat + " | " + "az devops login --organization "+organization
We tested this to validate it.

Running vulture from a python script

I'm trying to find a way to run vulture (which finds unused code in python projects) inside a python script.
vulture documentation can be found here:
https://pypi.org/project/vulture/
Does anyone know how to do it?
The only way I know to use vulture is by shell commands.
I tried to tun the shell commands from the script, using module subprocess, something like this:
process = subprocess.run(['vulture', '.'], check=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT,universal_newlines=True)
which I though would have the same effect as running the shell command "vulture ."
but it doesn't work.
Can anyone help?
Thanks
Vulture dev here.
The Vulture package exposes an API, called scavenge - which it uses internally for running the analysis after parsing command line arguments (here in vulture.main).
It takes in a list of Python files/directories. For each directory, Vulture analyzes all contained *.py files.
To analyze the current directory:
import vulture
v = vulture.Vulture()
v.scavenge(['.'])
If you just want to print the results to stdout, you can call:
v.report()
However, it's also possible to perform custom analysis/filters over Vulture's results. The method vulture.get_unused_code returns a list of vulture.Item objects - which hold the name, type and location of unused code.
For the sake of this answer, I'm just gonna print the name of all unused objects:
for item in v.get_unused_code():
print(item.name)
For more info, see - https://github.com/jendrikseipp/vulture
I see you want to capture the output shown at console:
Below code might help:
import tempfile
import subprocess
def run_command(args):
with tempfile.TemporaryFile() as t:
try:
out = subprocess.check_output(args,shell=True, stderr=t)
t.seek(0)
console_output = '--- Provided Command: --- ' + '\n' + args + '\n' + t.read() + out + '\n'
return_code = 0
except subprocess.CalledProcessError as e:
t.seek(0)
console_output = '--- Provided Command: --- ' + '\n' + args + '\n' + t.read() + e.output + '\n'
return_code = e.returncode
return return_code, console_output
Your expected output will be displayed in console_output
Link:
https://docs.python.org/3/library/subprocess.html

Python Error: print subprocess.check_output - invalid syntax

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))

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.

Why I got "sh: 1: Syntax error: Unterminated quoted string" when I run my Python program?

I want to count how many lines of code I have written.
Here is the Python code:
import os
import sys
EXT = ['.c','.cpp','.java','.py']
def main():
l = []
if os.path.isdir(sys.argv[1]):
for root, dirs, files in os.walk(sys.argv[1]):
l.extend([os.path.join(root, name) for name in files])
else:
l.append(sys.argv[1])
params = ["'"+p+"'" for p in l if os.path.splitext(p)[1] in EXT]
result = os.popen("wc -l %s "%" ".join(params)).read()
print result
if __name__ == '__main__':
main()
Before this, it was running as expected. But today, it give me this error:
sh: 1: Syntax error: Unterminated quoted string
I don't know what happened.
Your Python script is missing a shebang line. Add the following to the top of your file:
#!/usr/bin/env python
Then you should be able to run the following, assuming your script is at /path/to/your_script.py and it has the executable bit set:
/path/to/your_script.py arg1 arg2 [...]
Alternatively:
python /path/to/your_script.py arg1 arg2 [...]
Update following comments
I suspect what has changed is that a source file containing a ' in its name has been added to the directory you are checking and the shell is choking on this.
You could add the following function to your program:
def shellquote(s):
return "'" + s.replace("'", "'\\''") + "'"
[Lifted from Greg Hewgill's answer to How to escape os.system() calls in Python? .]
And call it like this:
params = [shellquote(p) for p in l if os.path.splitext(p)[1] in EXT]
#Johnsyweb's updated answer seems to have the correct diagnostic, but the correct fix is to not use a shell to invoke wc. Try something like this instead:
cmd = ['/bin/wc', '-l'] # Need full path!
[cmd.extend(p) for p in l if os.path.splitext(p)[1] in EXT]
result = os.popen2(cmd).read()
Note that the subprocess module is the recommended solution now. Switching to that requires a less intrusive change to your current code, though; see http://docs.python.org/2/library/subprocess.html#replacing-os-popen-os-popen2-os-popen3
Looks like your Python program was parsed like a shell script. Add something like this at the header to indicate where your Python is:
#!/usr/bin/python
or you just run python a.py.

Categories

Resources