« first day (3835 days earlier)      last day (1096 days later) » 

5:43 AM
dupe - can anyone suggest a target? pandas rolling average of last 7 days. I looked for decent targets but didn't find anything good. Time-based windows were only added in 0.18.2 (Jun 2016)
 
5:55 AM
@AnttiHaapala Just saw that exchange. We still often get people relying on 2.x code from books/blogs/courses/tutorials, and sometimes people who don't know what version their code examples are from. Probably worth adding a section to sopython.com/pages/chatroom
 
raf
6:31 AM
In FB messenger or in Whatsapp, there's a feature to reply to our own previous msgs. I feeling the necessity of that feature in SE chat rooms! Is there any way to do that now? or any chance of getting that feature? Does the feature have any drawbacks? Where should I talk about these types of feature request?
 
6:42 AM
I am trying to add some data to my Firebase database using python.
Here is my code:
for sym in sym_list: # sym_list = ['TCS', 'RELIANCE']
    close = df[sym][['Close', 'Adj Close']] # df is a pandas dataframe with row index as date
    for date, values in close.iterrows():
        db.reference(f'New/{sym[:-3]}/{date[:4]}/{date[5:7]}/{date}').set(json.loads(values.to_json())) # db is a firebase database
How to run this asynchronously to reduce the time?
 
7:15 AM
@raf You can do it in a slightly roundabout way, by clicking the dropdown icon to the left of your message, clicking permalink, and then copying the number portion at the end. then, you write :<your_permalink_number> <your_message> and it replies on your own post. try it in the sandbox
 
8:02 AM
@PoornaChandraR hiranya911.medium.com/… looks like it may help
 
raf
8:13 AM
@ParitoshSingh I got it. Thank you.
 
8:42 AM
@polka please use fewer newlines. If you have a question, write it up.
 
9:16 AM
Hey guys anybody here have experience with selenium and recieved the error: selenium.common.exceptions.WebDriverException: Message: invalid argument: can't kill an exited process
in the past? cannot figure whats going on here and have literally run the same set up as prior drivers
 
 
2 hours later…
11:03 AM
I want to sort a list of strings so that elements containing "foo" appear first. What's more readable, sort(key=lambda item: 'foo' not in item) or sort(key=lambda item: 'foo' in item, reverse=True)?
 
imo sort(key=lambda item: 'foo' in item, reverse=True)
 
@Aran-Fey former to me, plus comment
 
I guess both versions need a comment anyway, huh. No need to worry about it too much, then
 
11:59 AM
Yup
 
12:36 PM
I'm looking for a good reference or workflow for taking a task and building a GUI to serve said task. My current flow is to cobble something together and continuously change things until some level of organic functionality surfaces. Anyone have a reference for this sort of thing? Something more efficient than what I'm currently doing.
 
Mostly I just copy existing programs with similar functionality
 
That's a fair approach. Just sort think the study of that concept is potentially interesting and wondering if there was a known guru or source on the subject.
 
Yeah I would certainly be happy to see more literature on that kind of thing
I usually have trouble finding resources for the "softer" elements of software engineering. I don't know if my google fu is weak for more subjective topics, or if techie writers don't have much to say for things not directly involving code, or what
 
12:56 PM
Cbg-noon
quick question about unit testing
 
I may look into it. I'll mention anything I find worth reading. Putting things a bunch of people already know and do naturally into words can often be useful. Sometimes I see research that surprises me because it is novel only as a result of the fact that no one has ever bothered to previously document the thing or concept.
 
I think right now a lot of high level design knowledge exists only in the minds of the masters. Partly because programming is a relatively young craft, so there hasn't been much time to formally explore the unique challenges of the epistemology and pedagogy of development techniques. And partly because masters in any industry keep their trade secrets to themselves as long as there's a profit incentive to do so. Open source philosophy helps a little there, but there's a long way to go.
I think we're basically saying the same thing here :-)
 
I've created a function, which is usng the lib request to do a GET or a POST with a URL. I'm trying to create a unit test on the function. Issue is I don't know what I should view as a result, for this function and how to assert it.
 
@Kevin The best sources I have found on the "language" part of programming language design come from the BDFL of Perl. Soft issues very poorly documented, as far I can tell.
 
Thinking about it, the results should be the correct GET or POST of that function.
 
1:02 PM
@AndyK What part of it do you want to test?
 
The test should check that my function correctly did a GET or a POST
In short sentence, the result from that function.
 
When I'm not sure how to unit test something, that can be an indicator that I should refactor its return statement
 
In that case, run it against a well-known target and test the result.
 
If it isn't returning meaningful data, that could be a design problem in its own right
As a simple example, if your function isn't returning anything now, maybe you could make it return the HTTP response code from the server.
Then it's easy to test if the function succeeded, because it returns 200 OK
 
@Kevin actually, there are not return statement as I'm using the GET or the POST as such. However, if there was a return in my function, it also means that regardless of sucess or failure, the function will stop in the middle of a loop.
 
1:08 PM
If your function is making multiple requests in a loop and you want to execute all of them even if some fail, perhaps you could accumulate all the response codes in a list and return them at the end.
 
@Kevin that's brilliant! Thank you. I haven't thought about that one!
 
Reminds me of a somewhat silly design I needed to do a while back -- I needed to run ten functions in a row, and then indicate if one or more of them raised an exception.
errs = []
for f in funcs:
    try:
        f()
    except Exception as e:
        errs.append(e)
if errs:
    raise MultipleErrorsOcurredError(errs)
I ended up doing something like this
 
@Kevin that's first that I'm seeing a try in a loop. Wasn't aware of it.
 
I was frustrated that I couldn't get my custom MultipleErrorsOcurredError to elegantly display 10+ stack traces during a crash, but ultimately I didn't need it
 
but indeed, I got the idea.
 
1:14 PM
I don't endorse this specific design but it does get one thinking about more unconventional applications of exception handling
 
@Kevin Gonna love PEP 654...
 
@MisterMiyagi Ooh, neat
 
1:30 PM
cbg, I have asked something like this before and discovered it is bad practice, but is there a way I can tell if my list in a list comprehension is empty? without having to use enumerate to get the index? so I can apply a logic for empty list and non empty list
 
@python_user are you asking for something like a default if the list is empty?
 
could you give an example? which list are you referring to, the one that youre iterating on, or the one you're creating? in either case, seems like it would be easiest with a simple if condition before or after your comp as necessary.
 
ok let me create an MCVE
@MisterMiyagi the "list" there represent the list comprehension list
 
I don't know if I understand the question properly because I'm confused by the mention of enumerate here, so I'll just imagine you're asking "how can I concisely append a value to my list if (and only if) the list comprehension I used to create it doesn't have any elements?". I'm half tempted to suggest something like a = [b for c in d] or [e], but it's perhaps a bit too perl-ish for its own good
Taking advantage of the fact that or does not coerce its result to boolean is a fun party trick but I don't often use it in production quality code
 
@Kevin a = [b for c in d] or die Perl'd it for you
 
1:39 PM
or die is such a charming perlism :-) inject some life or death stakes into your program to spice things up
Petition to change exit() to perish()
 
The constant death threats in the first Perl program I ever saw were slightly irritating indeed.
 
seq = [0, 1, 2, 3, 4]
res = []
for i in seq:
    res.append('call foo(i)' if not res else 'call bar(i)')

res1 = ['call foo(i)' if not idx else 'call bar(i)' for idx, i in enumerate(seq)]
print(res1)
this is what I mean
in other words, is there a way I can tell if it is my first iteration in a list comprhension?
 
ah, you want to do something different for the very first element in the iteration?
 
yes, that is what I am trying
 
Oh, ok. It's not very easy to inspect the state of a list comprehension while it's still being built... IMO I think your enumerate strategy is fine.
 
1:47 PM
code.activestate.com/recipes/… I have asked regarding this here and this is what I mentioned bad practice, I guess it had to do with this, and it doesnt work anyways
I thought maybe knowing the list was empty or not would be similar to this
 
How do you feel about res1 = ["call foo(seq[0])"] + ["call bar(x)" for x in seq[1:]]
 
The "bad" part is that comprehensions represent "do <thing> on every element of <iterable>" aka map. Having an exception for any element breaks that.
Kevin's approach is what I'd do as well.
 
It's a tad inefficient, as is always the case for adding lists together, but if seq is small then meh
 
I have to deal with seq being an empty list now correct?
 
Pattern matching would make that easy...
drags himself behind the barn
 
1:49 PM
Yeah unfortunately you'd need to special-case an empty seq
 
thanks guys, I think I will stick with the enumerate approach then
 
Which can be as concise as res1 = ["call foo(seq[0])"] + ["call bar(x)" for x in seq[1:]] if seq else [] but now we're trending towards unreadability
I have a feeling you could do something cool with itertools.chain here
 
would pattern matching actually help here? out of curiosity
@Kevin I will see if I can hack something up with that
 
you could match the pattern [first, *tail] and []
 
Why does the first element in your list get special treatment? That's the real issue here
 
1:53 PM
If only we had car and cdr...
 
actually bar depends on a global variable that foo sets, and that is only set when this comprehension is run, I will refactor the old code to make sure bar deals with that and remove foo
 
match seq:
    case [head, *tail]:
        res = [f"call foo({head})"] + [f"call bar({t})" for t in tail]
    case []:
        res = []
That's.... actually longer than the if/else I would have written otherwise :/
if seq:
    seq_iter = iter(seq)
    return [f"call foo({next(seq_iter)})"] + [f"call bar({t})" for t in seq_iter]
 
I have to re read the pep for match, I was thinking it only applied to strings for some reason :/
result of having match as a name for regex search
 
import itertools

def foo(x): return f"foo({x})"

def bar(x): return f"bar({x})"

seq = "wxyz"
res = [f(item) for item, f in zip(seq, itertools.chain([foo], itertools.repeat(bar)))]
print(res) #['foo(w)', 'bar(x)', 'bar(y)', 'bar(z)']
Not beautiful IMO but here it is
I guess if you import the itertools funcs directly into your namespace, then zip(seq, chain([foo], repeat(bar))) doesn't look too unwieldy... YMMV of course
In any case, definitely don't use it if foo and bar aren't existing functions and you need to define them as inline lambdas
 
looking at that zip_longest kinda makes it less un readable
[f(item) for item, f in zip_longest(seq, [foo], fillvalue=bar)]
 
2:06 PM
!
I didn't know zip_longest had an argument like that. Nice find.
Now it's looking like something I would actually use in production :-)
 
laurel, itertools is also one of those things I have to look at the docs to remember the args
 
Might as well go for [... for item, first in zip_longest(seq, [True], fillvalue=False)] then
 
Or, hmm. Does this act weird if seq is empty...
 
@Kevin It will always produce at least one item :/
 
seq = []
res = [f(item) for item, f in zip_longest(seq, [foo], fillvalue=bar)]
print(res) #['foo(<function bar at 0x00452BF8>)']
Curses!
 
2:08 PM
ahh, I did not think of that
 
2:22 PM
Comedy option res = [f(item) for item, f in zip(seq, iter(lambda d={0:foo}:d.pop(0,bar),None))]
high levels of sin here, intentionally using the default mutable argument phenomenon, and having a dict with semantically meaningless keys
It's not my fault that list.pop doesn't have a what_to_return_if_not_found optional parameter, unlike dict.pop
 
hi guys do you guys talk django here as well
 
From time to time yeah
 
Hi, if you have a python related question you can ask here as long as it is within the rules
 
great thanks.
im facing issues with rendering django contexts into highcharts in the templates sections.. Anyone worked with the highcharts lib and django?
 
2:39 PM
I have not, but there are others users who use Django, so you may get a response sooner or later
 
2:50 PM
If your highchart initialization script is embedded directly within the html rather than being included via <script src=whatever>, then I'd expect it to be fairly straightforward for django to put information into it
Admittedly I have no professional experience with highcharts
 
3:11 PM
Don't you love it when you describe your problem and one guy says "idk sounds easy to me, just do it right"
 
3:32 PM
10/10 advice
 
As usual I can guarantee that my advice improves in quality if I'm provided an MCVE, but those are hard to construct when web frameworks are involved...
 
@Kevin having taken a look at the rabbit hole you all went down, i feel obliged to point out that you could have taken this, and used slicing for the first element as well instead of indexing it, and essentially have the problem solve itself.
res = [foo(val) for val in seq[:1]] + [bar(val) for val in seq[1:]]
something like that would handle empty seq just fine too, even though i think Aran probably had the most sense out of all of us combined, and essentially questioned why this behaviour would be needed in the first place.....but what's the fun in that!
 
@ParitoshSingh Good observation.
 
@Kevin Does it count if that one guy is myself? :/
 
i think in that scenario, that one guy can decide whether that advice by the one guy counts or not. it's just like a self-medal.
 
3:46 PM
@MisterMiyagi Yes
 
@ParitoshSingh Ouch. I knew I wasn't fun at parties, but apparently I'm no fun in a programmer chat room either. This is a serious blow to my self esteem! :P
 
@Aran-Fey on the contrary, you've got the "let me show you a cool party trick" down pat when it comes to programming quizzes, so by extension, you've probably got what it takes to be a show stopper in parties too. So, the only logical conclusion is that you're holding back so that others can take the spotlight
This logic makes sense to me, so it must be true. self-medal
 
To be honest, I've never been at a party. So there's a chance you might be right
 
4:01 PM
Programmers of the world, unite! But not in a physical sense. Stay at home in front of your computers where it's safe.
 
4:51 PM
I probably need to incorporate computer vision to account for the dead-reckoning-based error in my project, but I just _(:ι」∠)_
Damn it markup, don't turn my limbs into italics
If it works, error accumulation will drop to essentially zero, but it's such a labor investment
 
cabbage
 
5:10 PM
with argparse i get: UnboundLocalError: local variable 'words' referenced before assignment
would could be wrong?
 
That error usually occurs when you refer to a variable, e.g. do_thing(x), before you assign a value to it, e.g. x = 23
 
thx, yes.
I wanna have twot argparse arguments. python3 program.py -A -b
-b works
 
The simplest way to make the error go away is to do something like x = None at the top of the function. But odds are really good that do_thing will crash because it doesn't know how to handle a None, or it will behave strangely
 
@Kevin or... do_thing(x) before referencing the correct scope: global x :P wrt difficult variations
 
Yeah, getting your scopes confused can also cause this error
 
5:15 PM
without argparse else I print default value
 
@pythonabsir if you're still having trouble, upload a mcve to dpaste or pastebin and I'll be happy to give more specific advice
 
kevin'd
 
@Kevin thank you
 
Not quite an MCVE because there's no import statements, but I'll let it slide ;-)
In the if args.ignore: block, you do words = words_low #gives me list of word strings. What value should words have if this block doesn't execute? In other words, what if args.ignore is false?
 
@Kevin than the list of words 'words' is unchanged: like ['hi', 'Hi']
 
5:31 PM
Hmm. Where is ["hi", "Hi"] coming from? I don't see it in the code
 
@Kevin so words_low instead of words = words_low works
 
Inside if args.ignore:, you do print(len(words)). What is this supposed to print? You haven't created the words variable yet, so it can't possibly have a length.
 
@Kevin yeah, made it shorter , I have words variable outside the Main() function
 
Ok. I need you to include that in the pastebin too. An MCVE isn't an MCVE unless it's Complete.
 
@Kevin so I can still call words: if the last line of args.ignor is words_low
 
5:34 PM
Actually, before you go back to the drawing board, try putting global words at the first line of your Main() function and see if that helps
aneroid may have been on to something when he mentioned globals
If the global statement fixes things, it wasn't working before because Python assumes by default that any variable you assign to in a function is local, and it won't bother to look outside the function for any global variables with that name. So print(len(words)) means "look for the local variable named 'words', and print its length".
It doesn't matter that you have a global variable named "words" already, all Python cares about is that there isn't a local one. So it raises UnboundLocalError.
If you can't follow all of this, don't worry too much about it. It's usually easiest to just redesign your program so it doesn't use global variables. Then you don't have to learn any of this stuff :-)
 
Thanks for the updated pastebin. I'll see if my/aneroid's theory is close...
@pythonabsir Try this. The output looks OK to me, although admittedly I don't know exactly what you want
(You don't need that big string at the bottom by the way, that's just a comment)
Ah, you can also move words = ['there', 'Are', 'FEW', 'words', 'so', 'this'] inside Main(), and then you don't need the global statement. I like that way better. Rule of thumb: avoid using the global statement whenever possible.
 
@Kevin ah, tx, ah, thats it with the global statement. Is there any reason that with argparse -I I get 2 outputs? one from -I argparse and 1 from else, shouldnt I get just 1?
 
5:50 PM
I think you would need an if-elif-else chain for that. In other words, right now you have an if args.ignore: followed by if args.list: followed by else:. That else executes only when args.list is False, but it doesn't look at args.ignore's value at all.
If you want that final else to execute only when args.ignore is False and args.list is False, one way would be to change if args.list: to elif args.list:. Then the else only executes if both preceding conditionals failed
The drawback with this approach is that you can no longer see both -l and -I outputs at the same time, because the elif and else both get skipped if if args.ignore: is True
 
yea
 
I see you have a add_mutually_exclusive_group() call in a comment, so maybe you intended for it to be like that anyway, in which case it doesn't matter
If you do want -Il to print both outputs... Hmm, let me check the argparse documentation
 
changed it to
if not
2 times if not; than it works instead of else
@Kevin than it works
 
As in, you changed the else to if not args.ignore and not args.list:? Or something similar to that? Yes, I would expect that to work correctly.
I was looking through the argparse documentation to see if they had a more concise way of saying "if the user didn't give any arguments:", but I didn't see any. Maybe something like if not vars(args): would be OK, but I don't like using vars in serious code
stackoverflow.com/questions/14358753/… has some suggestions, including one similar to my vars idea. I actually like the lowest-voted answer the most, much to my surprise. Examining sys.args is concise and understandable.
But if you want to continue using your "2 times if not" design, that's perfectly fine
 
6:07 PM
@Kevin thx, great, the last one from Aiden Melen?
 
Yeah. I just upvoted it so it might have moved up the page
 
6:40 PM
@AndrasDeak You do realise that you just encouraged programmers to become extinct?
 
Life, uh, finds a way
 
Despite never interacting physically with other humans, programmers continue to propagate their genes by the "cool uncle" principle. They work to improve the fitness of their siblings and siblings' offspring, with whom they share 25-50% of their genes.
Examples of fitness optimization include: making sure hackers and nigerian princes don't steal anybody's life savings; buying fun gifts for the kids so they don't look for entertainment at the old flooded salt quarry
 
I'm worried about those Nigerian princes... they haven't emailed me in quite a while now.. hope they're okay...
 
Well, there's a finite number of them, so by now they've probably all successfully moved their trust funds out of the country and retired to the Carribbean with their American penpal, or they've been placed under house arrest by the nigerian government so they can't drain the country of their wealth
Thoughts and prayers for the latter category. Here's hoping it's a comfortably gilded cage, as is appropriate for royalty
 
6:57 PM
@AndrasDeak
0
Q: Can you use namedtuples/dataclass/attrs to create a flexible sized class for database api or do you have to use traditional classes?

polkaIf there is a json data set that looks like this. [ {'a':1,'b':'fire','c':'cambodia','type':'charizard'}, {'a':2,'d':'waterparks','type':'squirtle'}, {'a':3,'f':'thunder','type':'pikachu'} ] And it is needed to transition it into a set of objects where the objects can be defined with the same cl...

 
Hi there! Have you and Andras discussed this problem before? Because if not, it's rather odd to ping him for comment
 
he told me to create the question
 
I told them to stop streaming their consciousness here instead of asking a clear question
@polka not really
10 hours ago, by Andras Deak
@polka please use fewer newlines. If you have a question, write it up.
 
ok, well thanks anyway
 
message open to interpretation
 
6:59 PM
Hmm hmm I see
 
add a python tag to your question if you don't want it to die a lonely death
 
original question had more swearing because i am frustrated
 
good thing I didn't notice the swearing
 
:-P
 
@Aran-Fey done
 
7:01 PM
I suspect the answer to "can you use <thing> for a database api?" is usually "depends on the database api"
 
ugh, i was trying to add context, but it can really be dropped from the question
 
@polka for the record we ask that you don't ask for fresh questions on the main site in our rules, but you did sort of try your luck here first (even if your original wall of messages doesn't remind me of your current question). All things considered the world is better off that you've focussed your thoughts in a concise question on main.
@Kevin sounds like the starting point is the json-sourced dict
So unless this is an XY problem it might be irrelevant
 
Let me back up a bit. If the question is "If I'm writing my own database library that stores data in json files, can I use dataclasses?", I bet you could! If the question is "If I'm writing classes inheriting from SqlAlchemy's Base so i can interact with my existing database, can I usse dataclasses?", then I'm not so sure.
When you write everything from scratch, you can do almost anything
 
@AndrasDeak apologies. thank you for the update on the rules. i remember when there weren't no sticking rules... <3 it's better with the rules.
 
it's mostly for future reference
 
7:07 PM
Is there a way to suppress a specific mypy error globally? Like whats the command line to get rid of error: Cannot assign to a type ?
 
uninstalling mypy usually does the trick
 
#notmypy
 
lol
 
As far as I know mypy doesn't have global configuration. file-level is the highest it goes.
 
Yeah I've had a poor impression of mypy when I look at outcomes, it doesn't seem effective at catching many categories of errors. Much better to use runtime typechecking.
 
7:10 PM
@Mikhail "much better" is a bit surprising in this context
 
I mean, runtime typechecking checking will catch 100% of the type errors...
 
indeed
 
I do not envy the job of writing a static analysis tool for an implicitly strongly typed language like Python. Seems real hard.
@Mikhail As long as you execute 100% of code paths :-)
 
I'm surprised that a language that has millions of users has such poor static analysis tools
^Kevin I shoot most code paths on sight
 
@Mikhail how many people use javascript? My impression is that it's either hell, or typescript (a separate language).
 
7:12 PM
you'd be correct, thats why those exist
 
I am intrigued by your idea of branch-free programming and wish to subscribe to your newsletter
 
I'm sure there are static JS type checkers but I also suspect they are not universally used
 
finally I will be free from the tyranny of turing completeness
 
heh
that long-awaited python 3 update will arrive to you
 
death limits the size of the turing ticker tape
6
A: Is VHDL Turing complete?

PaebbelsAnother way to show turing completeness is a chain of transformations: Turing Machines are turing complete. Turing Machines can be simulated by register machines and vice versa. Register machines are an abstract and simple model of a modern processor You can describe a processor with VHDL So ...

on the note of turing completeness, here is a half baked discussion
 
7:20 PM
"suppose a JPEG photograph of a circuit can be converted into a VHDL, does this mean that JPEG Is turing complete?" -- By the mathematical universe hypothesis, there is literally no difference between a physical circuit and a sufficiently detailed description of that same circuit. Mystery solved.
In much the same way that print("Hello") prints "Hello" even though that code I just typed out is not being executed by any interpreter because it is inside a chat window and not a .py file being read by python.exe
ceci n'est pas une script
 
the code you typed isn't turing complete :-)
 
Turing, I've failed you ;_;
 
mypy says
`note: This violates the Liskov substitution principle`
^ is this some Isac Asimov stuff ;-)
 
Basically, except Asimov's laws have to be followed by computers, and Liskov's law has to be followed by OOP developers
Ultimately, both of them will keep a human from being shot in the foot
 
as a 10x I don't use OOP
DaTaDrIvEn
 
7:30 PM
In that case, you are exempt. Carry on with your business.
 
@Kevin I'm not sure about that... there's some very determined humans out there :p
 
I don't understand how a static analysis tool can verify that code adheres to the Liskov Substitution Principle, because you can only evaluate LSP correctness if you know the developer's subjective criteria for what the "desirable properties" of his classes are
You can't just say that the desirable properties are all publicly observable properties, because then inherited classes can't differ from their parents in any way, making them useless. Every language that has inheritance would automatically fail maximally strict LSP, because print(type(1)) doesn't produce the same output as print(type(object()))
mypy.readthedocs.io/en/stable/… mentions some examples of what it considers a desirable property (e.g. a subtype's method signature should not have any required paramaters that aren't present in the parent type's), but I'm not confident that it enumerates all of them here.
 
7:45 PM
I could find a specific code example that triggers this at gist.github.com/MattOates/33fa709d8313e59493647e1b492f6950
 
Hmm, I can't figure out what the error is complaining about. Both update() implementations have identical signatures.
supertype defines the argument type as "Observable". True! and so does the subtype, exactly as LSP desires
 
I'm surprised the error doesn't mention the wrong type, only what it's incompatible with
 
Hmm yep I'm totally lost
 
@Kevin if args.output:
f = open("fileout.out", "a")
f.write(str(args)) how do I write a f.write if I just wanna get whatever as output -o what I choose as other parser.argument -l and so
 
I also wonder about those strings as type names. That might be valid for typing but I'm pretty sure that's invalid inside isinstance
 
7:55 PM
@pythonabsir If I understand you correctly, you could redirect stdout to the file object. I'll make a small prototype in a minute.
Something like this:
import sys
from contextlib import redirect_stdout

output_to_file = False #try changing this to True and comparing what happens

if output_to_file:
    f = open("outfile.txt", "w")
else:
    f = sys.stdout

with redirect_stdout(f):
    print("Hello, world!")
If you don't feel comfortable with with, you could just specify the file object inline in all of your print calls. For example print("Hello, world!", file=f)
It won't capture any other output though, for example the messages that argparse prints for you when the user does the_script.py --help
brb
 
8:12 PM
Hello
 
@Kevin ok, added made first with redirect_stdout(f) below the if args.statements: , then tried to add print(f"{k} \t {v}", file=f) with ValueError: I/O operation on closed file.
@Kevin from contextlib import redirect_stdout is not used on my IDE
 
9:19 PM
@Kevin combining if args.output: with other arg.
 

« first day (3835 days earlier)      last day (1096 days later) »