I am learning to program in Python and am still at the very beginning.
I wrote a 2 scripts to cut out IP-addresses from a nmap-output.
The first script cuts out the IP-addresses:
import re
file = open("test.txt", "r")
ips = open("ips.txt", "w+")
for line in file:
ip = re.findall(r'[0-9]+(?:\.[0-9]+){3}', line)
if "filtered" in line:
ips.write(str(ip) + "\n")
This code works fine on Windows and Linux, but (I hope I'm right) the for-loop gets every line as a list. That means, my IP-addresses have the format ['x.x.x.x'].
I wrote a second script to delete all the unnecessary characters ([ ' and ]):
ip = open("ips.txt", "r")
ip_filtered = open("ip_filtered.txt", "w")
for line in ip:
s = line
neu = s.translate(({ord(i): None for i in '[\']'}))
ip_filtered.write(str(neu))
This script works well on Windows (I got a new file, just with IP-addresses), but on Linux I get the following error:
Traceback (most recent call last):
File "zeichen_loeschen.py", line 6, in <module>
neu = s.translate(({ord(i): None for i in '[\']'}))
TypeError: expected a string or other character buffer object
What's the reason for this error?
Thanks in advance :)
I get the same message when running with the python command on linux (which uses python 2.7). Try running it with the python3 command and your code should work.
Related
Learning python as a beginner. I wanted to copy my code into CMD but it won't work. Here is code
calculation_to_units = 24
name_of_unit = "hours"
def days_to_units(number_of_days):
if number_of_days > 0:
return f"{number_of_days} days are {number_of_days * calculation_to_units} {name_of_unit}"
else:
return "Liczba dni musi być dodatnia :)"
user_input = input("Hello user, enter amount of days you want to calculate to hours\n")
user_input_number = int(user_input)
calculated_value = days_to_units(user_input_number)
print(calculated_value)
despite the fact that it works in Pycharm. I already checked paths. I am not able to solve this problem. When I type in python3 test.py it also says C:\Users\Borys\AppData\Local\Programs\Python\Python310\python.exe: can't open file 'C:\Users\Borys\test.py': [Errno 2] No such file or directory
Also recieved this message "unable to initialize device prn in python"
My internet connection is so bad that it took me 10 minutes to sign up on stack overflow. Additionaly my english knowledge is too small for complex programming explainations.
It can be difficult to paste code that calls input() into a python shell. Both the shell and the input() function read stdin. As soon as python reads the line with input(), it calls input() and that consumes the next line on stdin. In your case, that was a python code line intended to set a variable. That line was consumbed by input and was not read or executed by python. So you got a "variable not defined" error. But you would also have gotten another error because that line was also not the stuff you wanted to input.
Suppose you had the script
val = input("Input value: ")
i_val = int(val)
print(i_val)
And pasted it into the python shell
>>> val = input("Input value: ")
Input value: i_val = int(val)
>>> print(i_val)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'i_val' is not defined. Did you mean: 'eval'?
The line i_val = int(val) was assigned to val - it was not interpreted by the shell. There would be an ">>> " if it did.
I know similar problems have been asked many times, but I don't think they solved my mine.
I'm basically trying to convert the following bash command into python using the subprocess module:
cat <a python file> | ssh <ip> python - <args>
Here's what I have:
with open('<the python file>', 'r') as python_file:
print(subprocess.check_output(['ssh', '<ip>', 'python - <args>', ], stdin=python_file))
And I'm running the above code from my local laptop using python3. When on the target machine (the remote server with <ip>) the python version is 2.7, this code snippet works fine. But if I switch the python version of the target machine to 3.4, I got the error:
File "<stdin>", line 114, in <module>
File "<stdin>", line 94, in main
File "<stdin>", line 22, in load
TypeError: 'str' does not support the buffer interface
I've tried the following:
open the python file with in binary mode: open('<a python file'>, 'rb')
change the subprocess args from ['ssh', '<ip>', 'python - <args>'] to ['ssh', '<ip>', 'python', '-', '<args>'].
But none of them worked. Can anyone give some suggestions? Thanks!
[Update]
Thanks to #Justin Ezequiel 's comment, this turned out to be a problem of '<the python file>' instead of the code snippet above. In '<the python file>' there is the following code:
columns = ['KNAME', 'TYPE', 'SIZE', 'MOUNTPOINT'] # (1)
lsblk_args = ['lsblk', '-i', '-n', '-o', ','.join(columns)] # (2)
output = subprocess.check_output(lsblk_args).strip() # (3)
parsed_res = _parse(output.split('\n'), columns) # (4)
And if I change the (3) line to
output = subprocess.check_output(lsblk_args).decode('utf-8').strip()
Everything works just fine.
I have Spyder 2.3.8 that I installed with Anaconda.
Python version is 2.7.11, conda version is 4.0.5.
I have found that some types of code make the Spyder editor stop responding. One example is the line:
x = b'\x89\x50\x4E\x47\x0D\x0A\x1A\x0A'
I assume this is a valid python code. I am relatively new to Python, so please correct me if I am wrong here. I tried in on a terminal on the Python shell and it works.
Another very strange example is
png = 'oxy.png'
f = open(png, 'rb')
f.read(10) # That executes without any problems
f.close()
f = open(png, 'rb')
x = f.read(10) # this line makes Spyder freeze!
f.close()
The only difference here is that I assign f.read() to a variable, and that makes Spyder stop responding!
I just updated Spyder and all other anaconda packages. The error was happening before and it still happens. Any idea of what I could be doing wrong, or what could I try?
EDIT: There was this other part of the question which has been explained already (thanks!)
I also tried to run the following example I found on the internet:
name = input("What is your name? ")
print("Nice to meet you " + name + "!")
This example gives me an exception. Here is the full output:
name = input("What's your name? ")
print("Nice to meet you " + name + "!")
What is your name? sininho
Traceback (most recent call last):
File "<ipython-input-1-e82cc0e3f7a3>", line 1, in <module>
name = input("What's your name? ")
File "/scr/elbe9/pauline/physio/program/python_libraries/anaconda2/lib/python2.7/site-packages/ipykernel/ipkernel.py", line 165, in <lambda>
builtin_mod.input = lambda prompt='': eval(self.raw_input(prompt))
File "<string>", line 1, in <module>
NameError: name 'sininho' is not defined
In Python 2, the input() function executes the code you type in. To get q string, use raw_input() function which works the same way.
I am trying to setup a program where when someone enters a command it will run that command which is a script in a sub folder called "lib".
Here is my code:
import os
while 1:
cmd = input(' >: ')
for file in os.listdir('lib'):
if file.endswith('.py'):
try:
os.system(str(cmd + '.py'))
except FileNotFoundError:
print('Command Not Found.')
I have a file: lib/new_user.py But when I try to run it I get this error:
Traceback (most recent call last):
File "C:/Users/Daniel/Desktop/Wasm/Exec.py", line 8, in <module>
exec(str(cmd + '.py'))
File "<string>", line 1, in <module>
NameError: name 'new_user' is not defined
Does anyone know a way around this? I would prefer if the script would be able to be executed under the same window so it doesn't open a completely new one up to run the code there. This may be a really Noob question but I have not been able to find anything on this.
Thanks,
Daniel Alexander
os.system(os.path.join('lib', cmd + '.py'))
You're invoking new_user.py but it is not in the current directory. You need to construct lib/new_user.py.
(I'm not sure what any of this has to do with windows.)
However, a better approach for executing Python code from Python is making them into modules and using import:
import importlib
cmd_module = importlib.import_module(cmd, 'lib')
cmd_module.execute()
(Assuming you have a function execute defined in lib/new_user.py)
I keep getting the following error:
$ ./test.py
-bash: ./test.py: cannot execute binary file
when trying to run the following file in python via cygwin:
#!usr/bin/python
with open("input.txt") as inf:
try:
while True:
latin = inf.next().strip()
gloss = inf.next().strip()
trans = inf.next().strip()
process(latin, gloss, trans)
inf.next() # skip blank line
except StopIteration:
# reached end of file
pass
from itertools import chain
def chunk(s):
"""Split a string on whitespace or hyphens"""
return chain(*(c.split("-") for c in s.split()))
def process(latin, gloss, trans):
chunks = zip(chunk(latin), chunk(gloss))
How do I fix this??
After taking on the below suggestions, still getting the same error.
If this helps, I tried
$ python ./test.py
and got
$ python ./test.py
File "./test.py", line 1
SyntaxError: Non-ASCII character '\xff' in file ./test.py on line 1, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details
There is a problem. You are missing the '/' in front of usr in #!usr/bin/python. Your line should look like this.
#!/usr/bin/python
In addition to protecting the file executable, #!/usr/bin/python may not work. At least it has never worked for me on Red Hat or Ubuntu Linux. Instead, I have put this in my Python files:
#!/usr/bin/env python
I don't know how this works on Windows platforms.