Python OptParser - python

I am trying to input a path using optparser in python. Unfortunately this piece of code keeps showing an error.
import optparse,os
parser = optparse.OptionParser()
parser.add_option("-p","--path", help = "Prints path",dest = "Input_Path", metavar = "PATH")
(opts,args) =parser.parse_args()
print os.path.isdir(opts.Input_Path)
Error :-
Traceback (most recent call last):
File "/Users/armed/Documents/Python_Test.py", line 8, in
print os.path.isdir(opts.Input_Path)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/genericpath.py", line 41, in isdir
st = os.stat(s)
TypeError: coercing to Unicode: need string or buffer, NoneType found
Any help is much appreciated !

That error is because opts.Input_Path is None, instead of being your path string/unicode.
Are you sure you are calling the script correctly? You should probably put in some error checking code in any case to make sure that if a user doesnt put -p, the program won't just crash.
Or, change it to a positional argument to make it 'required' by optparse:
http://docs.python.org/library/optparse.html#what-are-positional-arguments-for
Edit: Also optparse is deprecated, for a new project you probably want to use argparse.

I copied your script and ran it. Looks like you call your script in a wrong way:
$ python test.py /tmp
Traceback (most recent call last):
File "test.py", line 8, in <module>
print os.path.isdir(opts.Input_Path)
File "/usr/lib/python2.6/genericpath.py", line 41, in isdir
st = os.stat(s)
TypeError: coercing to Unicode: need string or buffer, NoneType found
but
$ python test.py --path /tmp
True

Related

How to search for text string in executable output with python?

I'm trying to create a python script to auto update a program for me. When I run program.exe --help, it gives a long output and inside the output is a string with value of "Version: X.X.X" How can I make a script that runs the command and isolates the version number from the executable's output?
I should have mentioned that I tried the following:
import re
import subprocess
regex = r'Version: ([\d\.]+)'
match = re.search(regex, subprocess.run(["program.exe", "--help"]))
print((match.group(0)))
and got the error:
Traceback (most recent call last):
File "run.py", line 6, in <module>
match = re.search(regex, subprocess.run(["program.exe", "--help"]))
File "C:\Python37\lib\re.py", line 183, in search
return _compile(pattern, flags).search(string)
TypeError: expected string or bytes-like object
Something like this should work:
re.search(r'Version: ([\d\.]+)', subprocess.check_output(['program.exe', '--help']).decode()).group(1)

What kind of object do I need to use the options parameter of fix_multiple_files?

I need to create a simple script for fixing indentation in python scripts of the repository. I found fix_multiple_files in autopep8 module:
import autopep8
autopep8.fix_multiple_files('/home/playrix/work/ci-teamcity/scripts/', options={'recursive': 1})
I'm getting this every time I run the script:
Traceback (most recent call last):
File "/home/playrix/work/ci-teamcity/scripts/1.py", line 4, in <module>
autopep8.fix_multiple_files('/home/playrix/work/ci-teamcity/scripts/', options='')
File "/home/playrix/.local/lib/python2.7/site-packages/autopep8.py", line 3897, in fix_multiple_files
filenames = find_files(filenames, options.recursive, options.exclude)
AttributeError: 'str' object has no attribute 'recursive'
How correctly noticed johnsharpe it was argparse.Namespace. And the best way to get it was:
opt = autopep8.parse_args(arguments=['recursive', '--in-place', '--aggressive'])

Python 3 [TypeError: 'str' object cannot be interpreted as an integer] when working with sockets

I run the script with python3 in the terminal but when I reach a certain point in it, I get the following error:
Traceback (most recent call last):
File "client.py", line 50, in <module>
client()
File "client.py", line 45, in client
s.send(bytes((msg, 'utf-8')))
TypeError: 'str' object cannot be interpreted as an integer
This is the code it refers to.
else :
# user entered a message
msg = sys.stdin.readline()
s.send(bytes((msg, 'utf-8')))
sys.stdout.write(bytes('[Me] '))
sys.stdout.flush()
I read the official documentation for bytes() and another source
https://docs.python.org/3.1/library/functions.html#bytes
http://www.pythoncentral.io/encoding-and-decoding-strings-in-python-3-x/
but I am no closer to understanding how to fix this. I realise that my msg is a string and I need an integer, but I am confused about how to convert it. Can you please help me, or direct me to a source that will help me?
Edit 1: I changed the line
s.send(bytes((msg, 'utf-8')))
to
s.send(bytes(msg, 'utf-8'))
but now I get the following error:
Traceback (most recent call last):
File "client.py", line 50, in <module>
client()
File "client.py", line 46, in client
sys.stdout.write(bytes('[Me] '))
TypeError: string argument without an encoding
Edit 2: According to #falsetru updated answer.
Using bytes literal gives me
TypeError: must be str, not bytes
Change the following line:
s.send(bytes((msg, 'utf-8')))
as:
s.send(bytes(msg, 'utf-8'))
In other words, pass a string and an encoding name instead of a passing a tuple to bytes.
UPDATE accoridng to question change:
You need to pass a string to sys.stdout.write. Simply pass a string literal:
sys.stdout.write('[Me] ')

os.command giving Attribute error

Hi I am trying to rum a C *.o using python 2.6.5 as follows
import os
import sys
file_type = os.command('./file_type.o %s.txt 2>&1' % file_name)
And, it gives the error message :
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'command'
Being a beginner this might be a very trivial question, I request for the direction / help.
There is no function named command in the os module, hence the error. You probably meant to call os.system() instead.
os.command() doesn't exist. It looks like you are looking for os.system()
os.command doesn't exist, using os.system instead.

Python os.remove failure (unicode object?)

My python script reads JSON information from a website, stores it in a file for processing, and should clean it in the end.
This was working without issues in other scripts, but for some reason, os.remove fails to delete the file in the end:
import urllib2, json
import os, sys, argparse
ref_list_tmpfile = '/tmp/reference.%s.txt' % os.getpid()
ref_list_response=urllib2.urlopen('http://localhost:11111/api/reference').read()
with open(ref_list_tmpfile,'w') as outfile:
outfile.write(ref_list_response)
ref_list_data=open(ref_list_tmpfile)
reference_list = json.load(ref_list_data)
ref_list_data.close()
.
.
.
.
os.remove(ref_list_tmpfile)
The main logic works well, but the error i'm getting refers to the last command (os.remove) and the file is not deleted:
Traceback (most recent call last):
File "./vm_creator.py", line 58, in <module>
os.remove(ref_list_tmpfile)
AttributeError: 'unicode' object has no attribute 'remove'
Any ideas?
You've redefined os to be a string, somewhere in the code you've snipped.

Categories