how do i make a line in a python executable in terminal? - python

#! /bin/python3
#Imports
import sys
import datetime
#Basic usage
print()
print()
print('Hello User. Welcome to ProjGURU, an innovative but basic project made by Unfree\'s CEO, Gururam. The current date and time is {}. Let\'s get right into the project.'.format(datetime.datetime.now()))
print()
lay1 = input('Please choose which programme to download and load.\n1.Tor\n2.Opera\n3.Chrome')
print()
#lay1 splitted
if lay1 == '1':wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
how do i execute the wget command

If your primary intention is to download that file, you can use the requests library, as Bruno pointed out in the comments. Install it via the command-line tool pip:
$ pip install requests
Then you can import the library and download your file as such:
import requests
# ... other code
if lay1 == '1':
with open('google-chrome-stable_current_amd64.deb', 'wb') as f:
r = requests.get('https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb')
f.write(r.content)

Related

Making a GUI File Downloader with Python 3 and Tkinter

(I am using python 3.6.6 if that matters to anyone)
I am making a GUI installer for a game that is currently in private alpha and is constantly updating.
I already made a console version:
from tqdm import tqdm
import requests, os, sys, zipfile, shutil, subprocess
chunk_size = 1024
url = "{LINK TO FILE YOU WANT TO DOWNLOAD}"
r = requests.get(url, stream = True)
total_size = int(r.headers['content-length'])
print("Are you sure you want to download the newest version of RFMP?")
print("y/n", end=': ')
answer = input()
while True:
if answer == 'y':
if os.path.exists("RFMB6_WINDOWS"):
print('')
print('')
print('Removing old RFMP files...')
subprocess.check_call(('attrib -R ' + 'RFMB6_WINDOWS' + '\\* /S').split())
shutil.rmtree('RFMB6_WINDOWS')
print('')
print('Removed old files.')
break
else:
break
elif answer == 'n':
sys.exit()
else:
print("That is not a valid answer, please answer with y/n.")
answer = input()
print('')
print('')
print('Downloading:')
with open('RFMB6_WINDOWS.zip', 'wb') as f:
for data in tqdm(iterable = r.iter_content(chunk_size = chunk_size), total = total_size/chunk_size, unit = 'KB'):
f.write(data)
print('')
print("Download Complete.")
print('')
print('')
print("Would you like to extract it?")
print("y/n", end=': ')
answer2 = input()
while True:
if answer2 == 'y':
print('')
print('')
print('Extracting...')
zip_ref = zipfile.ZipFile("RFMB6_WINDOWS.zip", 'r')
zip_ref.extractall("RFMB6_WINDOWS")
zip_ref.close()
print('')
print('Extraction Complete')
print('')
print('')
print('Cleaning up...')
os.remove("RFMB6_WINDOWS.zip")
print('')
print('Done! You have succesfully installed the newest version of the Ravenfield Multiplayer Private Alpha.')
break
elif answer2 == 'n':
print('')
print('Done! You have succesfully downloaded the newest Zip of the Ravenfield Multiplayer Private Alpha.')
break
else:
print("That is not a valid answer, please answer with y/n.")
answer = input()
os.system('pause')
I will only be using this to download 1 specific link so ignore the url variable.
I am trying to make a GUI that does the same thing when I click a button that says 'Download'. I want to make a progress bar, and a text box that tells you what is going on e.g. Downloading, extracting etc. I have no need for a directory option. I just need it to download where ever the file is located and delete the old file if it is still there.
So here is my question: How do I learn how to do this? I have looked at tkinter tutorials and other questions but I only find stuff for python 2 or stuff that is to developed to modify and call my own work. What I am looking for are links and/or examples that can tell me how I go about creating something like this. Thanks in advance to anyone who helps me out.
P.S. I am a noob when it comes to coding so whatever you explain please do it thoroughly.
P.S.S. In order to run the console application you need to run it through terminal and add your own link in the 'url' variable.
Take a look at PySimpleGUI. You can build a layout with a download button, an output window and a progress bar easily. Stop by the GitHub and post an issue if you run into trouble.
The documentation for Tkinter with Python3:
https://docs.python.org/3/library/tk.html
This answer might help you out:
How to create downloading progress bar in ttk?
documentation: https://tkdocs.com/tutorial/morewidgets.html#progressbar

No module named pathlib2

I've been working on getting Google Assistant working on my Raspberry Pi 3.
It is working but I'm having problems getting this specific step to work:
https://developers.google.com/assistant/sdk/guides/library/python/extend/handle-device-commands
This step covers sending an on/off command to the Pi to turn a LED bulb on or off.
I have confirmed the Bread board and LED is setup correctly because I can turn the LED on or off via a python script.
However, after following the steps in that page and trying to run the following command "python hotword.py --device_model_id my-model"
(which is actually: python hotword.py --device_model_id assistantraspi-1d671-pigooglev2-8n98u3)
I get the following error:
ImportError: No module named pathlib2
I am including a copy of that file (hotword.py)
#!/usr/bin/env python
# Copyright (C) 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
import argparse
import json
import os.path
import pathlib2 as pathlib
import RPi.GPIO as GPIO
import google.oauth2.credentials
from google.assistant.library import Assistant
from google.assistant.library.event import EventType
from google.assistant.library.file_helpers import existing_file
from google.assistant.library.device_helpers import register_device
try:
FileNotFoundError
except NameError:
FileNotFoundError = IOError
WARNING_NOT_REGISTERED = """
This device is not registered. This means you will not be able to use
Device Actions or see your device in Assistant Settings. In order to
register this device follow instructions at:
https://developers.google.com/assistant/sdk/guides/library/python/embed/register-device
"""
def process_event(event):
"""Pretty prints events.
Prints all events that occur with two spaces between each new
conversation and a single space between turns of a conversation.
Args:
event(event.Event): The current event to process.
"""
if event.type == EventType.ON_CONVERSATION_TURN_STARTED:
print()
print(event)
if (event.type == EventType.ON_CONVERSATION_TURN_FINISHED and
event.args and not event.args['with_follow_on_turn']):
print()
if event.type == EventType.ON_DEVICE_ACTION:
for command, params in event.actions:
print('Do command', command, 'with params', str(params))
if command == "action.devices.commands.OnOff":
if params['on']:
print('Turning the LED on.')
GPIO.output(25, 1)
else:
print('Turning the LED off.')
GPIO.output(25, 0)
def main():
parser = argparse.ArgumentParser(
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('--device-model-id', '--device_model_id', type=str,
metavar='DEVICE_MODEL_ID', required=False,
help='the device model ID registered with Google')
parser.add_argument('--project-id', '--project_id', type=str,
metavar='PROJECT_ID', required=False,
help='the project ID used to register this device')
parser.add_argument('--device-config', type=str,
metavar='DEVICE_CONFIG_FILE',
default=os.path.join(
os.path.expanduser('~/.config'),
'googlesamples-assistant',
'device_config_library.json'
),
help='path to store and read device configuration')
parser.add_argument('--credentials', type=existing_file,
metavar='OAUTH2_CREDENTIALS_FILE',
default=os.path.join(
os.path.expanduser('~/.config'),
'google-oauthlib-tool',
'credentials.json'
),
help='path to store and read OAuth2 credentials')
parser.add_argument('-v', '--version', action='version',
version='%(prog)s ' + Assistant.__version_str__())
args = parser.parse_args()
with open(args.credentials, 'r') as f:
credentials = google.oauth2.credentials.Credentials(token=None,
**json.load(f))
device_model_id = None
last_device_id = None
try:
with open(args.device_config) as f:
device_config = json.load(f)
device_model_id = device_config['model_id']
last_device_id = device_config.get('last_device_id', None)
except FileNotFoundError:
pass
if not args.device_model_id and not device_model_id:
raise Exception('Missing --device-model-id option')
# Re-register if "device_model_id" is given by the user and it differs
# from what we previously registered with.
should_register = (
args.device_model_id and args.device_model_id != device_model_id)
device_model_id = args.device_model_id or device_model_id
with Assistant(credentials, device_model_id) as assistant:
events = assistant.start()
device_id = assistant.device_id
print('device_model_id:', device_model_id)
print('device_id:', device_id + '\n')
GPIO.setmode(GPIO.BCM)
GPIO.setup(25, GPIO.OUT, initial=GPIO.LOW)
# Re-register if "device_id" is different from the last "device_id":
if should_register or (device_id != last_device_id):
if args.project_id:
register_device(args.project_id, credentials,
device_model_id, device_id)
pathlib.Path(os.path.dirname(args.device_config)).mkdir(
exist_ok=True)
with open(args.device_config, 'w') as f:
json.dump({
'last_device_id': device_id,
'model_id': device_model_id,
}, f)
else:
print(WARNING_NOT_REGISTERED)
for event in events:
process_event(event)
if __name__ == '__main__':
main()
Have you tried installing pathlib2 with pip or pip3? Please try
pip install pathlib2
if you're using Python2, and
pip3 install pathlib2
if you're using Python3. However, If pip is not found, then try installing it with
apt-get install python-pip python3-pip
Thanks for the suggestions. Turns out the solution was pretty simple.
The solution is two fold:
1: I have to run the following command first:
source env/bin/activate
Then I could run the python script without getting an error
(env) pi#raspberrypi:~/assistant-sdk-python/google-assistant-sdk/googlesamples/assistant/library $ python hotword.py --device_model_id assistantraspi-1d671-pigooglev2-8n98u3
As I progressed through the articles, the source becomes deactivated per se and returns to a normal prompt with first starting with (env).
Trying to run the python script without first loading the source command was the problem.
I still haven't wrapped my head around how this all works but I'll keep plugging along and hopefully understand what running this command first does
source env/bin/activate
This is the command that the script uses.
sudo apt-get install python-psutil
Make sure that you are working inside the virtual environment.
If not enter into the virtual environment and give a try.
If you are still having trouble execute the following command inside the virtual environment and try again:
sudo pip3 install pathlib2
This worked for me

Using python how to display dns

Using Python, is there a way using psutil or something else to return the output of "ipconfig /displaydns" or something similar?
Spawning a cmd process and running the command is not an option.
To execute a command, you can use the os library. Executing the command you've shown above is as simple as:
import os
os.system('ipconfig /displaydns')
If you want to store the output of a command in a variable, you can use:
x = os.popen('ipconfig /displaydns')
You can try using dnspython's resolver class, which has a nameservers list attached to it.
import dns.resolver
resolver = dns.resolver.Resolver()
resolver.nameservers
# Returns ['8.8.8.8', '8.8.4.4', '8.8.8.8'] on my pc
This python script I made creates a directory in widows user profile and copies windows dns information into a log.txt,So if directory does not exist it will create it. Hope it works for you.
#!/usr/bin/env python3
import time
import os
def dns():
path = os.system("ipconfig /displaydns >> %USERPROFILE%\DNS\logdns.txt")
if path == False:
os.system("ipconfig /displaydns >> %USERPROFILE%\DNS\logdns.txt")
print("Please wait copying information........")
time.sleep(5 )
os.system("cls")
print("Information copy complete.")
time.sleep(3)
else:
print("Making directory please wait a second....")
time.sleep(5)
os.system("cls")
os.system("mkdir %USERPROFILE%\DNS")
time.sleep(1)
dns()
dns()

how to provide username and password while checking out the code from SVN using python script without third party module

I am able to write a script to checkout the code from SVN issue using "pysvn" module but just wanted to know is there any way I can do without pysvn also ? Because pysvn is third party library which I have to install separately on linux and windows both which I don't want. Please help me get alternate way in which I don't have to install any third party module code -
import pysvn,os,shutil
def getLogin(realm, username, may_save):
svn_user = '<my-username>'
svn_pass = '<my-password>'
return True, svn_user, svn_pass, False
def ssl_server_trust_prompt( trust_dict ):
return (True # server is trusted
,trust_dict["failures"]
,True) # save the answer so that the callback is not called again
def checkOut(svn_url,dest_dir):
if os.path.isdir(dest_dir):
shutil.rmtree(dest_dir)
os.mkdir(dest_dir)
client = pysvn.Client()
client.callback_ssl_server_trust_prompt = ssl_server_trust_prompt
client.callback_get_login = getLogin
client.checkout(svn_url,dest_dir)
else:
os.mkdir(dest_dir)
client = pysvn.Client()
client.callback_ssl_server_trust_prompt = ssl_server_trust_prompt
client.callback_get_login = getLogin
client.checkout(svn_url,dest_dir)
print "Checking out the code hang on...\n"
checkOut('<svn-repo>','ABC')
print "checked out the code \n"
print "Checking out the code hang on...\n"
checkOut('<svn-repo>','XYZ')
print "checked out the code\n"
print "Checking out the code hang on...\n"
checkOut('<svn-repo>','MNP')
print "checked out the code \n”
You can pass username and password as arguments:
$ svn update --username 'user2' --password 'password'
You can make Executable of ur script which will include the pysvn into binary file, thus wouldn't need to import or pip install any library, n ur code will run on python-less machines too

How do I retrieve the current song name and time left from pianobar using python?

I'm creating an alarm clock with a gui using TKinter and python on my raspberry pi. When the alarm goes off I want it to start playing pianobar. I can do this easily enough, but I also want to display the name of the song on the GUI, and I cannot figure out how to get the current song being played. I have tried using pipes "|", and redirecting with ">" but I have gotten nowhere. Any advice will help.
You need to use the event command interface. From the man page:
An example script can be found in the contrib/ directory of pianobar's source distribution.
~/.config/pianobar:
user = <username>
password = <password> (although I'd suggest password_command)
event_command = ~/.config/pianobar/event_command.py
~/config/event_command.py
#!/usr/bin/env python
import os
import sys
from os.path import expanduser, join
path = os.environ.get('XDG_CONFIG_HOME')
if not path:
path = expanduser("~/.config")
else:
path = expanduser(path)
fn = join(path, 'pianobar', 'nowplaying')
info = sys.stdin.readlines()
cmd = sys.argv[1]
if cmd == 'songstart':
with open(fn, 'w') as f:
f.write("".join(info))
This will write the song information to ~/.config/pianobar/nowplaying when a new song starts (there are other events available in the manpage). You can then parse that using your choice of tools to acquire the song title.

Categories

Resources