Currently, this code works. It creates a text file named SerialNumber that saves in pictures. The problem is I can't seem to work out how to get it to work on any computer. So for example, if I remove \users\Jarvis from the file path it no longer finds its way to pictures. I'm trying to get it to work no matter who is logged in.
import os
Save_Path='C:\\Users\\Jarvis\\Pictures\\SerialNumber.txt'
with open(Save_Path, 'w') as f:
f.write(str(os.system('start cmd /k "wmic bios get serialnumber >C:\\Users\\Jarvis\\Pictures\\SerialNumber.txt"')))
I've tried to set it as:
\users\Admin
\users%UserProfile%
\users\user
but that returns
FileNotFoundError: [Errno 2] No such file or directory:
import os
from pathlib import Path
Save_Path= 'C:\\Users\\Pictures\\SerialNumber.txt'
path = Path.home() / "Pictures\SerialNumber.txt"
with open(path, 'w') as f:
f.write(str(os.system('start cmd /k "wmic bios get serialnumber >C:\\Users\\%UserProfile%\\Pictures\\SerialNumber.txt"')))
With Subprocess and replace I was able to print to python just the serial number
import subprocess
SerialNumber = 'wmic bios get serialnumber'
result = subprocess.getoutput(SerialNumber)
print(result.replace("SerialNumber", ""))
Okay after some help, and research, This is the final code. It uses a subprocess that will output to python>CMD. I then used re (lines 7 and 8) to .strip and re.sub removing everything that wasn't actually the serial number. I installed pyperclip to copy
import subprocess
import pyperclip
import re
import os
SerialNumber = 'wmic bios get serialnumber'
result = subprocess.getoutput(SerialNumber)
SerialResult = (result.strip("SerialNumber"))
print(re.sub("[^a-zA-Z0-9]+", "", SerialResult))
pyperclip.copy(re.sub("[^a-zA-Z0-9]+", "", SerialResult))
Related
import os ,fnmatch
import os.path
import os
file_dir= '/home/deeghayu/Desktop/mec_sim/up_folder'
file_type = ['*.py']
for root, dirs,files in os.walk( file_dir ):
for extension in ( tuple(file_type) ):
for filename in fnmatch.filter(files, extension):
filepath = os.path.join(root, filename)
if os.path.isfile( filepath ):
print(filename , 'executing...');
exec(open('/home/deeghayu/Desktop/mec_sim/up_folder/{}'.format(filename)).read())
else:
print('Execution failure!!!')
Hello everyone I am working on this code which execute a python file using a python code. I need to save my output of the code as a text file. Here I have shown my code. Can any one give me a solution how do I save my output into a text file?
Piggybacking off of the original answer since they are close but it isn't a best practice to open and close files that way.
It's better to use a context manager instead of saying f = open() since the context manager will handle closing the resource for you regardless of whether your code succeeds or not.
You use it like,
with open("file.txt","w+") as f:
for i in range(10):
f.write("This is line %d\r\n" % (i+1))
try
Open file
f= open("file.txt","w+")
Insert data into file
for i in range(10):
f.write("This is line %d\r\n" % (i+1))
Close the file
f.close()
I have main.py file which will accept 2 arguments, create a setup.py file and use this file to create standalone application ie .exe file by using Pyinstaller as follows:
main.py:
import sys
import argparse
parser = argparse.ArgumentParser(description='Display full name.')
parser.add_argument("-f", '--firstname', type=str, default='', help='first name.')
parser.add_argument("-l", '--lastname', type=str, default='', help='Last name.')
parsed_args = vars(parser.parse_args())
first_name = parsed_args['firstname']
last_name = parsed_args['lastname']
print("Hello " + first_name + " " + last_name)
setup.py:
from distutils.core import setup
import py2exe, sys, os
sys.argv.append('py2exe')
firstname = 0
lastname = 0
if '--firstname' in sys.argv:
index = sys.argv.index('--firstname')
sys.argv.pop(index)
upload = sys.argv.pop(index)
if '--lastname' in sys.argv:
index = sys.argv.index('--lastname')
sys.argv.pop(index)
token = sys.argv.pop(index)
print("firstName:", firstname)
print("lastName:", lastname)
setup(
console=['main.py'],
script_args=[firstname, lastname],
)
I created setup.exe file by using command:
pyinstaller setup.py --onefile
I tried to execute the command as:
setup.exe --firstname "CLMSS" --lastname "BGMDDS"
Here I passed 2 arguments as like used while running main.py. So for this getting error as:
The system cannot execute the specified program.
Can you help on this, How to resolve this issue? OR How to make as .exe file as accepting commands.
Might not be the solution you're looking for but for anyone else having trouble with this, I suggest you use sys.argv[1] to get the arguments instead of using argparse to get your arguments. It works just as well and plays very friendly with .exe execution on cmd
I have some python code that will extract names from a given link
from lxml import html
import requests
from bs4 import BeautifulSoup as bs
import re
import sys
import os
import lxml.html
#url = sys.argv[1]
page = requests.get('https://streaming.ine.com/c/ine-comptia-a-plus-220-902')
tree = lxml.html.fromstring(page.content)
#name for each video
names = tree.xpath('//div[#class="cd-timeline-level"]/text()')
#sys.stdout = open("D:\\mytext.txt", "w")
print (*names)
The printed output is :
Course Introduction
Compare & Contrast Microsoft Operating Systems
Installing Windows PC OS
Applying Appropriate Microsoft Command Line Tools
But i want to be more like this :
01.Course Introduction
02.Compare & Contrast Microsoft Operating Systems
03.Installing Windows PC OS
04.Applying Appropriate Microsoft Command Line Tools
Whitout spaces between lines. :)
You can strip whitespaces and format text using code like this:
names = filter(lambda n: n.strip(), names)
for index, name in enumerate(names):
print('{}. {}'.format(index, name.strip()))
I'm creating a script which can find movies from more than one site and play the movie with subtitle : server.py have all the information how to find the websites that have movies and the file have more than one function. Then I created a folder in the same directory with the server.py. This folder holds more the one website.py this files have the rules how to locate the movie file from the movie website my problem is that I'm importing functions from the server.py to this files exp : (
"""import server
server.org_link""") when I import the same function to the second file I get an error (AttributeError: module 'server' have no attribute 'org_link')
when I remove from the second file and I run server.py all work normally
(I cant find out what the problem is)
import os
import subprocess
import server # im importing this to the second file
from selenium import webdriver as wb
from selenium.webdriver.firefox.options import Options
option = Options()
option.headless = True
"""Set option headless to use with firefox"""
browser = wb.Firefox(options=option)
"""Set The browser WebDriver FireFox"""
with browser as driver:
driver.get(server.org_link)
element = driver.find_element_by_id('DtsBlkVFQx').get_attribute('innerHTML')
movie_link = server.hosted_server + '/stream/' + element
if os.name != 'nt':
vlc = subprocess.Popen([os.path.join("vlc"),os.path.join(movie_link)])
else:
vlc = subprocess.Popen([os.path.join("C:/", "Program Files(x86)", "VideoLAN", "VLC", "vlc.exe"), os.path.join(movie_link)])
Make:
server.org_link()
Instead of:
server.org_link
I have the following python-script, which open a text-file:
import sys
file = r"D:/...../text.txt"
with open (file,"r") as infile:
text = infile.read()
print (text)
If I want to run this script on another computer, i have to change the path (the same text-file "text.txt" will be saved on the other computer). Is there any way to let my script search the computer for the text-file without writing the path in the script?
Thank you.
Have you tried putting it in a relative directory, e.g.:
import sys
file = r"text.txt"
with open (file,"r") as infile:
text = infile.read()
print (text)
Just keeping the text file in the same directory as the small program.
You can use glob to get the result you want, but the glob will return a list of files, you may need to adapt your code.
Using a GUI for "choose file"
import sys
from Tkinter import *
import tkFileDialog
master = Tk()
master.withdraw() #hiding tkinter window
file_path = tkFileDialog.askopenfilename(title="Open file", filetypes=[("txt file",".txt"),("All files",".*")])
with open (file_path,"r") as infile:
text = infile.read()
print (text)