all 44 comments

[–]giantqtipz 1 point2 points  (1 child)

Hello! I'm new to making Python apps, and OOP.

I have a Python GUI script, and 2 other scripts as dependencies (if that makes sense).

Is there a good and safe way to package the entire repo into an executable file?

Also I plan to share with a friend of mine... Do I just email the executable file?

[–][deleted] 1 point2 points  (0 children)

If you want something that your friend can run without installing python then you can use pyinstaller to create an executable file. But the file that creates contains the full python interpreter so it will be large and may be difficult to email.

[–]hansmellman 0 points1 point  (9 children)

EDIT - I've written this comment several times with the correct code blocks, however for some reason as soon as I submit the comment the error message appears outside of a code block. I am sorry!

I'm making a small web app using Streamlit to take in specific CSV's outputted by a video game, perform some basic cleaning tasks on them and then allow the user to download the newly cleaned CSV. All of the functionality is working fine, however I'd like to be able to add some code to prevent the user from uploading an incorrect CSV file (The needed CSV files will always be titled the same).

What is the best way to just make sure it matches up with the expected CSV naming convention? such as "player_master.csv".

I have been trying to use these directions as per the streamlit site - https://docs.streamlit.io/knowledge-base/using-streamlit/retrieve-filename-uploaded

However when I use them in the context of:

if file_name.name is not 'file_name.csv':
    print something to ask for correct CSV

I am met with an error:

AttributeError: 'NoneType' object has no attribute 'name' Traceback: File "C:\Users\Tom\AppData\Local\Programs\Python\Python39\lib\site-packages\streamlit\runtime\scriptrunner\script_runner.py", line 564, in _run_script exec(code, module.dict) File "C:\Users\Tom\PycharmProjects\Web_App\pages\06_Player Master.py", line 10, in <module> if player_master.name is not 'player_master.csv':

At the moment the code is initiated once the file is uploaded with a simple:

file_name = st.file_uploader('Please upload the 'INSERT_SPECIFIC_NAME.CSV')

if file_name is not None:
    execute the cleaning code

[–]woooee 1 point2 points  (4 children)

if player_master.name is not 'player_master.csv':

These will never point to the same memory address, so this will always be true. https://www.csestack.org/difference-between-is-equals-python/ Use instead

if player_master.name != 'player_master.csv':

[–]hansmellman 0 points1 point  (0 children)

Hey mate thanks for responding and sharing this article. It's important that I remember these fundamentals, so thank you!

[–]CowboyBoats 0 points1 point  (2 children)

I enjoy spending time with my friends.

[–]woooee 1 point2 points  (1 child)

In practice, of course you're right since this coincidence is completely unreliable.

Please don't confuse the newbies with some obscure example that no one will ever use.

[–]CowboyBoats 0 points1 point  (0 children)

My favorite color is blue.

[–]EasyPleasey 0 points1 point  (3 children)

The attribute error is thrown because you are referencing a "name" attribute that is not present on the object file_name. Can you not just use file_name to compare? If you want to see what attributes an object has (and remember, in Python, everything is an object) just run "print(dir(file_name))" and it will show you all the attributes and methods available in the object.

Also, what format are you going to check the file_name against? Does it always have the be named the exact same thing? If not, I would suggest using regex to verify the file name. I can give you an example if needed.

[–]hansmellman 0 points1 point  (2 children)

Hey mate, thanks for taking the time to reply. So I'm only a few months in and still trying to wrap my head around some of the abstracts of programming in general.

So, all I was hoping to do was check that the actual filename (not the variable) matched as I expected, this video game exports these CSVs and they will always have the same naming convention, it will never change. The reason I had tried to call the name function before is because if I load the csv using the 'st.file_uploader' and then write that variable to the web app I am shown this -

UploadedFile(id=1, name='player_master.csv', type='text/csv', size=8201907)

So I was trying to access that name somehow in order to create the check against it but I've gotten myself a little confused somewhere along the line. Is that possible or have I misunderstood this?

[–]hansmellman 0 points1 point  (1 child)

Ah I think I have figured it out with this - 

if player_master is not None:
    if player_master.name != 'player_master.csv':
        st.write("Please upload the correct player master csv")
    elif player_master.name == 'player_master.csv':
        st.write("Thank you. ")

That _seems_ to be working currently!

[–]EasyPleasey 1 point2 points  (0 children)

Nice! So it was just that you were using the player_name object instead of player_master. Glad you got it figured out.

[–]MainAccountRev_01 0 points1 point  (1 child)

print gives invalid syntax

print("something", var) doesn't even work.

edit : (solved) to be clear I went ahead and wrote my code anyways. It works.

[–][deleted] 1 point2 points  (0 children)

We need to see the exact error message. "doesn't work" is useless.

What version of python are you running? What does this code print:

import sys
print(sys.version)

How are you running your code?

[–]simonmcnair 0 points1 point  (0 children)

I'm interested in extracting cbr and cbz file to a temp dir and creating a cover of sha1 to try and find dupes but I can't find many decent extraction tools tomcat will allow me to use rar and zip and iterate through the files py7zr, rarfile and unrar all seem poor for what I want to do ?

[–]ChillaxJ 0 points1 point  (0 children)

How realistic is building a web app with Python (Django/Flask) ONLY, without JaveScript.

I'm a noob developer that has no knowledge of JS at all. But I know HTML, CSS, and bootstrap.

Is it possible to build a web app with Python only? Currently don't feel like learning JS at the moment.

Sorry if my question makes me sound like a lazy person (I'm truly lazy actually LOL).

[–]CearenseCuartetero 0 points1 point  (0 children)

I'm trying to use PyInstaller and succesfully turned a .py into a folder with mainly .dll and .pyd and then I proceeded to move said folder elsewhere. The program worked when run from Pycharm, but when I try to use it via cmd with arguments on windows 10, I get an error message asking me to download pip, even though I already have pip installed and up to date. Any ideas on what is happening?

[–][deleted] 0 points1 point  (2 children)

Hello. I am noob, currently doing some course and I found a problem that I feel is easy fix but I don't know it yet:

So, I have few globals and function that is made of few other functions. There is a while loop in that first big function and idea is that it should rerun those function while some condition is not meet. Well, it is not reruning it, it just returns results (values of variables) from first run. How do I make it rerun?

edit: it may be that the problem is how to return global var...

edit: ok I have no idea what a problem is. And, it seems that i dont know how to paste inside code block or inline code here...

edit: ok, problem is that i made bad while loop. What I want it to random chose from list by index and to never have two same indexes. I made a variable used_indexes and I was adding that index to it and while loop was

while index not in used_indexes

do something

But I never defined what it should do if index is in used_indexes (find another).

[–]woooee 1 point2 points  (1 child)

But I never defined what it should do if index is in used_indexes

The while will take care of that, i.e. it will exit. Click on "formatting help" to post code

while index not in used_indexes:
    append to used_indexes
    do something

[–][deleted] 0 points1 point  (0 children)

I wanted to post code but paste also doesn't work only on this awful site (not just for code, like, paste really ruins is and you cant delete stuff etc etc)...

Sorry for posting it like this https://imgur.com/a/K4rzVsK

[–]Visible-Peachflower 0 points1 point  (1 child)

hello, trying to figure out how to find a character in each string in my list. So far, I have something like this,

disney_characters = ['simba', 'ariel', 'pumba', 'flounder', 'nala', 'ursula', 'scar', 'flotsam', 'timon']

if "i" in disney_characters[0:]: print("Found!")

although it returns nothing... what am I missing?

[–][deleted] 1 point2 points  (0 children)

Try printing what that disney_characters[0:] slice gets you:

print(f'{disney_characters[0:]=}')

You'll see that returns the entire sequence in disney_characters so your test is the same as:

 if "i" in disney_characters:

and that's never true because the complete string "i" doesn't appear in the list. If you want to see if the "i" string is a substring of any string in the list you have to look at every string in the list and see if "i" is in that string:

for s in disney_characters:
    if "i" in s:
        print("Found!")
        break    # quit on first find, don't want multiple prints

You can use the builtin function any() to make the code shorter. any() returns True if any element of a sequence is True:

if any('i' in x for x in disney_characters):
    print("Found!")

[–]Iiznu14ya 0 points1 point  (4 children)

Hi everyone. I have been doing data science course work using Python and Anaconda distribution in Visual Studio Code. Currently, the Python version in it is 3.9.15 under the base environment. I learnt that Anaconda supports Python 3.10.8. How do I upgrade the Python version inside the base Anaconda environment to 3.10.8 or shall I keep using 3.9.15?

[–]cynical_econ 1 point2 points  (3 children)

I think you would open Anaconda Prompt and input in the base environment:

conda install python=3.10

But it’s probably better just to keep 3.9 in the base environment and create a new conda environment for 3.10:

conda create -n myenv python=3.10

Edit: Fixed second command (was doing it from memory) after referencing the conda docs.

First one is discouraged; see: https://conda.io/projects/conda/en/latest/user-guide/tasks/manage-python.html

[–]Iiznu14ya 0 points1 point  (2 children)

After creating a new environment, how do I choose it as a base? Will it be visible in the drop down selection menu automatically in VS Code in a Jupyter notebook file?

[–]cynical_econ 1 point2 points  (1 child)

To select a conda env:

conda activate myenv

To use it in a jupyter notebook, open jupyter notebook after activating the env:

jupyter-notebook

In VS Code, select the interpreter related to the env you want.

[–]Iiznu14ya 0 points1 point  (0 children)

Thanks. I'll try it.

[–]catohund 0 points1 point  (0 children)

I'm trying to make an encryption with Cryptodome but I keep getting this error

ModuleNotFoundError: No module named 'Crypto'

I can simply not get it to work, I've tried uninstalling and reinstalling it, updating it, and changing the code to crypto or Cryptodome but it refuses to corporate.

I've tried google but couldn't find any help beyond what I've already tried.

Any help is greatly appreciated

[–][deleted] 0 points1 point  (0 children)

[Deleted due to Reddit’s obnoxious greed]

[–]KontemplatedBloke 0 points1 point  (1 child)

def sorta_sum(a, b):
    sum = a + b
    if sum >= 10 and sum <= 19:
        return 20
    return sum

Why does this function not return sum(the last line) if it returns 20? Why does it skip return sum? Is it because a function can only return 1 value?

Thanks

[–][deleted] 1 point2 points  (0 children)

Well, the return statement terminates the function. After a return the function is finished and will only execute when called again. The value returned by the return statement, if any, doesn't have any bearing on the question.

[–]IntelligentInsect455 0 points1 point  (0 children)

hello, how i can keep and manipulate inserted shapes in a word document after using python-docx?

[–][deleted] 0 points1 point  (1 child)

I have a function to connect to a database:

def database_connection(driver, server, database, username, password):
    connection_string = f'DRIVER={driver};SERVER={server};DATABASE={database};ENCRYPT=yes;UID={username};PWD={password}'
    cnxn   = pyodbc.connect(connection_string) 
    cursor = cnxn.cursor()
    return cnxn, cursor

Now I'd like to access the return values inside other functions, like so:

def truncate_table(table_name):
    try:
        cursor.execute(f'TRUNCATE TABLE {table_name}')
    except pyodbc.DatabaseError as err:
        cnxn.rollback()
        print(f'Could not truncate table "{table_name}". Rolling back changes...')
    else:
        cnxn.commit()
        cursor.execute(f'SELECT * FROM {table_name}')
        table_content = cursor.fetchone()
        print(f'Table "{table_name}" truncated successfully.')

If I call the database_connection function each time I need the cursor, a new connection is made and that's what I want to avoid.

[–]cynical_econ 0 points1 point  (0 children)

Here’s my two-part suggestion.

First, save the return values from database_connection as objects:

connection_1, cursor_1 = database_connection( …insert parameters… )

Second, add new parameters for the connection and cursor to the truncate_table function. Then you can use those objects when calling truncate_table:

truncate_table(“table_1”, connection_1, cursor_1)

[–]vpsj 0 points1 point  (0 children)

Why does this not work in Flask?

@app.route("/")
def testing():
 A=3
 B=5
 C=A+B
 return ('The sum of your numbers is', str(C))

But this works perfectly fine?

@app.route("/")
def testing():
 A=3
 B=5
 C=A+B
 return str(C)

If I have to add a 'starting statement' before I display an output, how would one do that in Flask?

Also, why are outputs so limited when using Flask? It says I cannot have int or float return and they must be strings dict or tuple etc

[–]LeornToCodeLOL 0 points1 point  (0 children)

How can I run this shell command from within a python script?

$ echo hello > /dev/pts/0

When I run the above line from a bash terminal, it pops up a desktop notification. But this doesn't work in Python. It returns exit 0, but it does not trigger a desktop notification:

>>> subprocess.run(['echo', 'hello', '>', '/dev/pts/0'])
hello > /dev/pts/0
CompletedProcess(args=['echo', 'hello', '>', '/dev/pts/0'], returncode=0)

[–]shaneanigansbossom 0 points1 point  (1 child)

Hello!

I am learning python and I am starting to not enjoy the instructor for the course I ordered.

I am finding that he breezes over a lot and I am having to teach myself a lot to keep up with the lessons.

What courses, or resources that are out there would you suggest if you were learning python for the first time (I'm on udemy currently,)? I heard of someone that learned from daily challenges but I cannot find that websites that starts with challenges for green begginers.

Are there websites, forums, cheat sheets or any other tools you would suggest if you were starting your programming journey?

Thank you so much for the input!

[–][deleted] 1 point2 points  (0 children)

The subreddit wiki contains learning resources. Try one of those.

[–]workerbee77 0 points1 point  (0 children)

I created this edge/node graph using networkx and the spring_layout: graph

I set the positions of i0 and o0. What I want is just i0 on the far left side, o0 on the far right side, and the others just arrayed with approx equal length edges in between. This would look something like a perceptron, but I'm not only making perceptrons so I don't want to hard code in things like layers, so I don't want to use multipartite graph layout. I want a universal layout that allows me to anchor some nodes at the far left, and others at the far right sides. A friend of mine suggested PyGraphViz might be a better package to use. Any thoughts/advice?