Short for loop for fetching bash users - python

A short python script i wrote to fetch users who are using bash. below is script. I don't know why its not working. Please share your ideas as to how this program is working inside.I am beginner in python and looking for lectures on data structures and algorithms. any answers are welcome. Thanks
f = open("/etc/passwd")
mainshell = '/bin/bash'
for line in f:
field = line.split(:)
shell = field[-1]
user = field[0]
if shell = mainshell:
print(user)
edit: I am getting no output. I tried to fetch values of variable shell and users and that exactly what i need but somehow if block is not working. Its not giving any error but just not working.

You are almost there with your script. But there are 2 reasons why its not working.
Your if statement is not doing a string comparison. You should be using == not =
You compare the string mainshell with shell, but you assume shell does not contain whitespaces. But the string will probably look like this /bin/bash (notice the whitespaces at the end?). This can be removed with shell = field[-1].strip()
I think then your program should work fine :)

Related

SQLite3 (Python): execute() command not working with string parameters

I'm writing code that takes a user-inputted string and binds it to a SQLite command through a parameter.
I've gotten this functionality to work when the string is already embedded in the query (see first example under "these lines do work"), and this binding method works with integers just fine (see second example).
testname = "\"EJtheDJ\"" #this would be user-inputted, but I get the same issue when I initialize it this way
#this line doesn't work
c.execute("select lastfm from usernames where discordname=?", (testname,))
#these lines do work
#c.execute("select lastfm from usernames where discordname=\"EJtheDJ\"")
#c.execute("select integer1 from test where integer2=?", (num,)) #num=3
print(c.fetchone()) #prints out "None"
My syntax seems 100% correct according to all the tutorials and forum threads I've looked at. I don't normally make posts here (in fact this is my first time), but I'm completely stumped on this and felt it was my only option. Any help would be massively appreciated. I'm running this on a CentOS server with Python 3.6, if that helps.
Edit: Turns out I just needed to do away with the escaped quotes. testname = EJtheDJ works perfectly.

Python - Code Query

When I type the following code through command prompt in python, I get an error.
When I type the same in Atom and run via script, the code runs.
Can anyone advise what could be a problem here. Thanks.
Code:
city = 'kolkatta'
count = 0
for blah in city:
if blah=='l'
count=count+1
print (count)
You have to insert an empty line after count=count+1.
Continuation lines are needed when entering a multi-line construct. As
an example, take a look at this if statement:...
from 2.1.2. Interactive Mode

Having trouble playing music using IPython

I have the lines of code
import IPython
IPython.display.Audio(url="http://www.1happybirthday.com/PlaySong/Anna",embed=True,autoplay=True)
And I'm not really sure what's wrong. I am using try.jupyter.org to run my code, and this is within if statements. The notebook is also taking in user inputs and printing outputs. It gives no error, but just doesn't show up/start playing. I'm not really sure what's wrong.
Any help would be appreciated. Thanks!
First you should try it without the if statement. Just the two lines you mention above. This will still not work, because your URL does point to an HTML page instead of a sound file. In your case the correct URL would be 'https://s3-us-west-2.amazonaws.com/1hbcf/Anna.mp3'.
The Audio object which you are creating, will only be displayed if it is the last statement in a notebook cell. See my Python intro for details. If you want to use it within an if clause, you can use IPython.display.display() like this:
url = 'https://s3-us-west-2.amazonaws.com/1hbcf/Anna.mp3'
if 3 < 5:
IPython.display.display(IPython.display.Audio(url=url, autoplay=True))
else:
print('Hello!')

Parse only given values to command line via Python

I'm sending I'm receiving a JSON message through MQTT in Python, and I would like to start a command line program with what the JSON gives as variables.
The problem with this is that I don't know what values are going to come through and thus this is where I have trouble.
The easiest would be if I knew all the variables that would come through and do something like this:
data = json.loads(msg.payload)
os.system("'command +f ' + data[arg1] + ' +g ' + data[arg2]")
But as mentioned previously, I don't know if they are being passed through, and as such, how can I break it down so that the command line command is build up?
Maybe:
if 'arg1' in data:
command = "+f " + data[arg1]
else:
pass
if 'arg2' in data:
command + "+g " + data[arg2]
else:
pass
Would this work? Is there a better idea?
You can use a for loop to iterate over the json, and construct the command string.
commandArgs = ["+f ","+g "]
commandCount=0
for element in data:
command= command + commandArgs[commandCount] + element
commandCount = commandCount +1
Although you could do this as described it's not something you should do. Running user-inputted commands is one of the most unsecure things a program can do. Scrubbing the commands thoroughly is possible but quite difficult to do comprehensively. The usual approach is to have a table of acceptable commands, match against the table, and then use the entries from that table to populate the command line. Nothing typed by the user ever makes it into the command line with that method.
If you do wish to take user input directly, be extremely careful about scrubbing all special characters, characters outside your preferred locale, double-byte characters, path delimiter characters, etc. Perhaps you could start with the snippet Jeff provided and add a lot of data scrubbing code.
Also, be aware that the probability that whatever you do not code for will eventually be submitted for processing corresponds roughly to the risk of that command. For example, if you fail to catch and remove cat ~/.ssh/* there's a moderately good chance one of your users will execute it or someone will break in and do so. But if you do not catch and remove rm -r /* the chance someone will submit that command approaches certainty.

Separate functions in python?

I'm not sure if function is the word I am looking for. In fact I don't really know what I'm saying but I have some code and it's not quite doing it what I want to. Basically I want to copy and paste this code I've got and email it to someone. I want them to be able to simply copy and paste it into their Terminal and perform calculations.:
## SCSAC.py
def round(x, base=5):
return int(base * round(float(x)/base))
option = 'yes'
while (option == 'yes'):
x=float(raw_input('How many accumulated orders do you have from retailers: '));
y=float(raw_input('How many units are in the inventory: '));
z=float(raw_input('How many accumulated orders have you placed: '));
print 'Place an order of %s units' % round(((x / 25 + y / 10 + z / 25) + 115));
print ;
option=raw_input("Do you wish to calculate another order? (Enter 'yes' to continue or any other key to quit):: ");
print
Whenever I type this code in line for line, it works perfectly. That's because there are basically 3 seperate things happening here.
I define "round" which rounds a value to the nearest 5.
I define an option to loop the program upon completion
I define the actual program, and in that I round the answer and conclude with the option to loop. You may notice 2 print's that don't print anything, but they are only there to have blank lines.
When I copy and paste it, I get a syntax error.
I am not a programmer and I have just been playing with this all day. I just want to know how I can edit this code so it is copy/paste-able and will run the way it is supposed to.
Try using IPython instead of the regular Python interpret at the shell. With IPython, you can type %cpaste, and then paste a whole chunk of code, which it will execute for you step by step, saving the intermediate variables into working memory.
If you insist on pasting it in the regular interpreter, then do it line by line, and take special care for the indentations. The indentations are usually where paste syntax errors come from.
Even better, use Emacs. Then you can just save the pasted code into a file, like test.py, type M-x shell, and then python test.py to quickly run it. Or, if you saved it to a file like test.py then in IPython you can also type %run "test.py" and it will run the code and again store intermediate variables into working memory.
If you're copy/pasting this after making changes more than once or twice, just save it to a file and run it like a script.
You can save the code in a file, and run it using Python.
You can add #!/usr/bin/env python to the beginning of the file, so it can run on *nix systems (if you have execute permission).
Or, you can do python SCSAC.py and run your code. This works on all systems (AFAIK). You can email the file to your person, and she can run it using Python. This seems to be the easiest way to do it.

Categories