Syntax error whenever i try to use sys.stderr - python-3.x

I've got a problem using the standard error, whenever I try to use it my computer gives me a syntax error which i can't explain.
So this is my code:
import sys
def main(argv):
if len(argv) != 3:
print("Usage: python walk.py n l", file=sys.stderr)
else:
l = argv[2]
n = argv[1]
print("You ended up", simuleer(n,l), "positions from the starting point.")
if __name__ == "__main__":
main(sys.argv)
And this is my error
MacBook-Air-van-Luuk:documents luuk$ python walk.py 5 1 2
File "walk.py", line 21
print("Usage: python walk.py n l", file=sys.stderr)
^
I hope someone can explain me why this happens, thanks in advance!

You think you're using Python 3.x, but it's actually Python 2.x. On most systems python executable means Python 2.x.
print is not a function in Python 2.x, and can't be used like that, causing a syntax error.
You should look for some way to run Python 3.x instead.
For this particular case, you could also use from __future__ import print_function, which would make the code compatible with both versions.

There is a way to fix it
Just remove the "file=" from print method
e.g:
print("Usage: python walk.py n l", sys.stderr)

Related

trying to print output using sys.stdout, but not able to print same as it coming none

I am trying to print output using sys.stdout but getting none on stdout. please check
# Read input from STDIN. Print output to STDOUT
import math
import os
import random
import re
import sys
def stdin(s):
if (len(s)>=2 and len(s)<=10000):
ev=[s[i] for i in range(len(s)) if i%2==0]
od=[s[i] for i in range(len(s)) if i%2!=0]
even=''.join(map(str,ev))
odd=''.join(map(str,od))
sys.stdout.write("{0} {1}".format(even,odd)) #print outpout using stdout but error got
sys.stdout.flush()
if __name__ == '__main__':
s = input().strip()
stdin(s)
By default python uses stdout when using the built in print() function. It will also read from stdin when using input(). I would suggest going that route as it will be less prone to error. Otherwise could you share the exact error message you are getting? The code is running without error for me.

Capturing runpy.run_module stdout

I'm unable to capture stdout of runpy.run_module into a variable using StringIO.
To demonstrate the problem, I created a script called runpy_test.py (code below) using an arg switch;
0 = do not redirect stdout.
1 = redirect using StringIO, capture into variable, print variable.
Console Output
(base) PS C:\Users\justi\Documents> python .\runpy_test.py 0
pip 20.0.2 from C:\ProgramData\Anaconda3\lib\site-packages\pip (python 3.6)
(base) PS C:\Users\justi\Documents> python .\runpy_test.py 1
(base) PS C:\Users\justi\Documents>
I was expecting python .\runpy_test.py 1 to print pip 20.0.2 from C:\ProgramData\Anaconda3\lib\site-packages\pip (python 3.6), but as you can see from the above console capture, I'm getting nothing.
runpy_test.py
import io
import sys
import runpy
import copy
capture_stdout = bool(sys.argv[1] == "1")
if capture_stdout:
_stdout = sys.stdout
sys.stdout = io.StringIO()
_argv = copy.deepcopy(sys.argv)
sys.argv = ['', '-V']
runpy.run_module("pip", run_name="__main__")
sys.argv = _argv
if capture_stdout:
result = sys.stdout.getvalue()
sys.stdout = _stdout
print(f"result: {result}")
I'm guessing sys.stdout is not being correctly re-initialised before I print because of something related to runpy.run_module, but not really sure how to debug. Any ideas would be great, solutions even better.
My environment is Python 3.6.10 using conda 4.8.3.
Thanks in advance.
Using subprocess.check_output instead of runpy.run_module solved my problem.
See Installing python module within code
You can use capsys in the pytest framework:
def test_main(capsys):
runpy.run_module(
"helloworld",
init_globals=None,
run_name="__main__",
alter_sys=False)
captured = capsys.readouterr()
assert captured.out == "Hello, World!"

How to run the python file in Spark

I am having python code in python file.I want to know how to run the python code which is present in one location.I am using Ubuntu OS.In my code, I am getting Json from one URL and need to show as scatter graph using SPARK.I am new to PYSPARK. Please guide me how to achieve this. Please find my below code,
`import multiprocessing
import time
import json
from sseclient import SSEClient as EventSource
# 'Complete your function here i cant understand what you are doing'
# i just placed the code inside check once i dont have the package so u try it
def func(n):
file = open('w.txt','w',encoding='utf8')
url = 'https://stream.wikimedia.org/v2/stream/recentchange'
print(1)
url = 'https://stream.wikimedia.org/v2/stream/recentchange'
json_st=''
stt=''
for event in EventSource(url):
if event.event == 'message':
try:
change = json.loads(event.data)
except ValueError:
pass
else:
print(1)
file.write(str(event.data))
#if file.write(str(event))count <= 10:
#print(event.data)
#print(event.data)
#js=json.loads(event.data)
##print(js['comment'])
#file.write(stt)
#print(stt)
#file.write(str(event))
# count = count + 1
#else:
# break
#print(stt)
#json_str={s}
if __name__ == '__main__':
# Start your process as a process
p = multiprocessing.Process(target=func, name="func", args=(10,))
p.start()
# Wait 3(give your time in secs) seconds for foo
time.sleep(3)
# Terminate func
p.terminate()
# Cleanup
p.join()`
you have to used spark-submit command to running you python script with spark (using command line terminal).
spark-submit /home/sample.py

Why no call_at_threadsafe and call_later_threadsafe?

I'm using Python 3.5.2 in Windows 32bits and aware that asyncio call_at is not threadsafe, hence following code won't print 'bomb' unless I uncomment the line loop._write_to_self().
import asyncio
import threading
def bomb(loop):
loop.call_later(1, print, 'bomb')
print('submitted')
# loop._write_to_self()
if __name__ == '__main__':
loop = asyncio.get_event_loop()
threading.Timer(2, bomb, args=(loop,)).start()
loop.run_forever()
However I couldn't find a piece of information about why call_at_threadsafe and call_later_threadsafe is implemented. Is the reason ever exists?
Simply use loop.call_soon_threadsafe to schedule loop.call_later:
loop.call_soon_threadsafe(loop.call_later, 1, print, 'bomb')

function to write on stderr with python2 and python3

I'm writing a program that ought to work with both python2 and python3.
For this, I would like to have a function to write to stderr that works with both python versions.
Ideal I think would be something like:
def writeStdErr(message):
if sys.version_info >= (3, 0):
print(message, end = "", file = sys.stderr)
else:
sys.stderr.write(message)
the problem with this that python2 is, that print isn't a function, so I get
print(message, end = "", file = sys.stderr)
^
SyntaxError: invalid syntax
I could get rid of this by just adding eval:
def writeStdErr(message):
if sys.version_info >= (3, 0):
eval('print(message, end = "", file = sys.stderr)')
else:
sys.stderr.write(message)
however, I dislike this solution; I think it's general a bad idea to use eval.
Does anyone knows something better/has a better solution?
EDIT:
For anyone having the same problem in future, the following things seem works:
def writeStdErr(message):
sys.stderr.write(message)
or
from __future__ import print_function
import sys
def writeStdErr(message):
print(message, file=sys.stderr)
Thanks to all answers
If you are using Python2.7, you can import the new behaviour:
from __future__ import print_function
That should be the first line of code (but could go after a shebang).
Another alternative compatible with earlier versions is to create it in an external module.
if sys.version_info >= (3, 0):
from print_sderr3 import writeStdErr
else:
from print_stderr2 import writeStdErr
where you have implemented each one accordingly.
That is to answer your question, BUT, you can just use sys.stderr.write for both. The only difference is that in Python 3 it seems to return the number of characters written. If you do it on interactive mode:
>>> sys.stderr.write('aaaa\n')
aaaa
5
You get an extra 5, but that is just the return value.
>>> a = sys.stderr.write('aaaa\n')
aaaa
>>> a
5

Resources