w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories
Redirect output of a .bat file run by a python script to GUI, and making that script into EXE
You could use the subprocess module to call your script Example calling the 'ls' command on Linux: >>> from subprocess import call >>> call(['ls', '-l']) total 0 -rw-rw-r-- 1 user group 0 Jun 17 18:37 file1 -rw-rw-r-- 1 user group 0 Jun 17 18:37 file2 -rw-rw-r-- 1 user group 0 Jun 17 18:37 file3 0

Categories : Python

To redirect output to log file and also accept user input in same batch script
If you want only certain parts of your script to be logged, just use >> SQL_LOGS.txt on those specific lines in your script (rather than using it on your call to the script). As for prompting the user for a specific response, give this article a quick read: http://www.quepublishing.com/articles/article.aspx?p=1154761&seqNum=12 EDIT - here's a batch script inspired by the above link that should help exemplify your goal. @echo off echo This is an example of accepting user input and writing some output to a log. :again set /p answer=Do you want to run a sql script (Y/N)? if /i "%answer:~,1%" EQU "Y" goto logit if /i "%answer:~,1%" EQU "N" exit /b echo Please type Y for Yes or N for No goto again :logit echo sql script goes here. this command's response is sent to th

Categories : Batch File

How do I output a .pdb file using python script?
This example code appears to do what you want: Relevant part is: import sys from Bio.PDB import PDBIO from Bio.PDB.PDBParser import PDBParser PDB_input = sys.argv[1] parser = PDBParser() structure = parser.get_structure('self', PDB_input) # DELETED CODE THAN MANIPULATED PDB OBJECT w = PDBIO() w.set_structure(structure) w.save('corrected_from_CHARMM_to_PDB.pdb')

Categories : Python

Processing output of python file called inside a bash script
If you mean the output of python, you should test it with $() instead #!/bin/bash if test "$(python /var/lib/scripts/Hudson.py result)" = "Success" then Run next command else Exit the script fi And it's actually better with [[ ]] #!/bin/bash if [[ "$(python /var/lib/scripts/Hudson.py result)" == "Success" ]] then Run next command else Exit the script fi If you mean the exit code: #!/bin/bash if python /var/lib/scripts/Hudson.py result then Run next command else Exit the script fi

Categories : Linux

Create output file names based on input file name with autonumbers shell script linux
VAR="INPUTFILENAME" # One solution this does not use the VAR: touch INPUTFILENAME{1,2,3,4,5,6,7,8,9,10} # Another for i in `seq 1 20` ; do touch "${VAR}${i}" done And there are several other ways.

Categories : Linux

sys module giving different output when running Python script through IDLE and by double-clicking the script
print os.path.dirname(sys.executable) is what you should use. When you click it it is probably running through python.exe so you are removing the extra char from the w.

Categories : Python

Run python file within python script, passing arguments
I would try doing somehting like this. os.system("appcfg.py arg1 arg2 arg3") I would look into this portion of the os documentation. Goodluck.

Categories : Python

How to write the results of a batch file called in a Python script to a file
Why are you calling list2cmdline? This doesn't actually call the subprocess. Use subprocess.check_output instead: import os output = [] for _, _, files in os.walk(directory): for f in files: fullpath = os.path.join(directory, os.path.basename(f)) output.append(subprocess.check_output([fullpath])) print ' '.join(output)

Categories : Python

Invoke python script from another python script and set execution directory of the executed script
You could use cwd parameter, to run scriptB in its directory: import os from subprocess import check_call check_call([scriptB], cwd=os.path.dirname(scriptB))

Categories : Python

What do I do to make a python script that can run from any directory: the script file doesn’t have to be in the same directory as the .csv files?
Assuming you mean to include a fixed CSV file with your code, store an absolute path based on the script path: HERE = os.path.dirname(os.path.abspath(__file__)) csv_filename = open(os.path.join(HERE, 'somefile.csv') __file__ is the filename of the current module or script, os.path.dirname(__file__) is the directory the module resides in. For scripts, __file__ can be a relative pathname, so we use os.path.abspath() to turn that into an absolute path. This means you can run your script from anywhere. If you meant to make your script work with arbitrary CSV input files, use command line options: import argparse if __name__ == '__main__': parser = argparse.ArgumentParser('CSV importer') parser.add_argument('csvfile', type=argparse.FileType('w'), default

Categories : Python

How to sort a csv file through python script?
If I'm not mistaken the "a" tag opens for writing in this line: with open("csv_file.csv", "a") as inputfile: This means you're opening for writing, not for reading. You should use either "r" or "+".

Categories : Python

how to pass variable from python to shell script when shell script is getting called inside python script
You can: Step through the list, and then call mail.sh once for each file. This is the most reliable way. Convert the items in the list to a space delimited string, and then pass it in to mail.sh (assuming mail.sh is setup correctly, it should accept multiple arguments). What you cannot do is pass ['a.txt','b.txt','c.txt'] wholesale to the script.

Categories : Python

On Mac, how to create a drag & drop app for a python script where the script name rather than Python shows in the MenuBar (etc.)?
I have an answer to my question, but I am hoping that someone can come up with something less complex. The solution I came up with was a Python script to create an AppleScript (ugh!), compile it into a bundle and then modify the bundle to change the allowed file extension(s), the icon and so on. I did not find a way to get drag-and-drop working when starting a wxpython script, without an AppleScript (or using py2app) and I could not get the AppleScript to work in a bundle I created, I had to use osacompile to create the bundle for me. I like better the approach here or here, where one creates the plist file "by hand" rather than than modify an externally created one as I do here, but the script below does do the job. #!/usr/bin/env python '''This script creates an AppleScript app to

Categories : Python

zsh: how to autocomplete file names after python script name?
Honestly, IMO something in your shell configuration is breaking things up. Try doing this to verify it: zsh -f # starts a new shell ignoring your configuration autoload compinit compinit ./my-shell-script [TAB] it completes with files. That is the default. FWIW, if you want to bind a particular completer to a command/alias etc, you can do compdef _jstack jstack # simple _files completion compdef _files my-local-python-script # restrict to some file extensions compdef '_files -g "*.(eps|ps|pdf)"' okular

Categories : Osx

Issue on reading a CSV file into FME through a startup python script
Did you have a look at the file that your python script writes to your disk? This might at least show you why there is a difference. I don't think this has anything to do with FME. In FME2013 you can directly use the reader to access a web-based source dataset. This works for any file-based format and even zipped data. So you don't need to use the python-script to download the file before.

Categories : Csv

How to get a file on a memory stick read into a python script?
Since you don't explicitly open the file yourself, the simplest thing to do in this case would be to just make sure that the path to the file you pass asciitable.read() is valid. Here's what I mean: import asciitable import os from string import ascii_uppercase import sys PATH_TEMPLATE = '{}:/ECBGF/bg0809_protected.txt' for drive in ascii_uppercase[:-24:-1]: # letters 'Z' down to 'D' file_path = PATH_TEMPLATE.format(drive) if os.path.exists(file_path): break else: print 'error, file not found' sys.exit(1) x = asciitable.read(file_path, guess=False, delimiter=' ', fill_values=[('', '-999')])

Categories : Python

How I do get a python script that I run on a .cvs file locally, to work on MS SQL table?
You'll definitely need to rewrite the code and use python MSSQL driver: pyodbc or pymssql. Also, take a look at sqlalchemy sql toolkit and object relational mapper. It can help you to build an abstraction layer so that it would be easier for you to switch between different database backends in the future. Hope that helps.

Categories : Python

Trying to store raw bytes inside my one Python script file
You should encode the binary - for example, using base64 encloding - to turn the bytes into "legitimate characters". Then, when you need the binary information, you convert it back. See for example this earlier question for some code examples. A brief sample to get you going: # assume your bytes came from a file: bytesIneed = bytearray([234,232,231,188,122,132,145]) import base64 bytesConverted = base64.b64encode(bytesIneed) print "encoded string: " print bytesConverted bytesRecovered = base64.b64decode(bytesConverted) print "decoded binary: " for c in bytesRecovered: print(ord(c)) This will return the following output: encoded string: 6ujnvHqEkQ== decoded binary: 234 232 231 188 122 132 145 As you can see - the string 6ujnvHqEkQ== can be stored anywhere; and the decoding funct

Categories : Python

Import variable from Python script to Batch file
In Python Create a temp batch file in %TEMP%setvars.bat containing SET commands to set environment vars. You could use subprocess.POpen to run an ECHO something > path batch command so that %TEMP% can be used. In Batch Call the temp batch file : the vars are now available to use.

Categories : Python

python script to concatenate all the files in the directory into one file
You can iterate over the lines of a file object directly, without reading the whole thing into memory: with open(fname, 'r') as readfile: for line in readfile: outfile.write(line)

Categories : Python

How to extract data from a text file with python script?
You could try something like this: whole_data = [] grab_lines = False with open('input','r') as atom_file: molecule_data = ['23 '] for line in atom_file: if line.startswith('coordinates'): grab_lines = True continue elif line.startswith('velocities'): grab_lines = False if molecule_data: #just checks that we aren't appending an empty list. molecule_data.append(' ') whole_data.append(molecule_data) molecule_data = ['23 '] if grab_lines: #in python 'is True' is implicit for many types. molecule_data.append(line) with open('output','w') as out_file: for molecule in whole_data: out_file.write(''.join(molecule)) I copy/past

Categories : Python

Python script to unzip and print one line of a file
I am assuming that: You meant to have quotes around the file name in your script. You actually want the third line (as your post suggests) and not the third character (as your script suggests) In this case the following should work: import gzip data = gzip.open('pagecounts-20130601-000000.gz', 'r') data.readline() data.readline() print data.readline()

Categories : Python

In python, can I find the file name of the script being executed, instead of __main__?
I think sys.argv[0] is your best bet - it should work from any module, not only the main module. Note that this may or may not be a full path and you'll have to test for "-c", the empty string, and otherwise use os.path.abspath to get a full path.

Categories : Python

How can I find the currently executing script file and path in python?
In case __file__ is not set, you can get the directory via import sys, os script = os.path.abspath(sys.argv[0] or 'unknown script') directory = os.path.dirname(script))

Categories : PHP

Jenkins runs imported python script before main python script
The child process flushes its output buffers on exit but the prints from the parent are still in the parent's buffer. The solution is to flush the parent buffers before running the child: print("Starting script...") sys.stdout.flush() build.run()

Categories : Python

unable to Raise a "File Download" Dialog Box using python cgi script
HTTP header terminate early. (print itself write newline) print "Content-Type:application/octet-stream; name="sqlite3.db" "; print "Content-Disposition: attachment; filename="sqlite3.db" "; Abobe lines should be: print 'Content-Type:application/octet-stream; name="sqlite3.db' print 'Content-Disposition: attachment; filename="sqlite3.db' print

Categories : Python

Running a python script through PHP and redirecting stdout, stderr to file
i think you need to use >& instead of &> see details below ">" Redirect standard output ">&" Redirect standard output and standard error "<" Redirect standard input ">!" Redirect standard output; overwrite file if it exists ">&!" Redirect standard output and standard error; overwrite file if it exists "|" Redirect standard output to another command (pipe) ">>" Append standard output ">>&" Append standard output and standard error

Categories : PHP

Catch Python script output in PHP and avoid double output
You can try with exec function. It also performs a command execution but, at diference fo system, doesn't output the content to standard output. The only drawback is that the return is an array of every line in the stadard output (not a string, like system. You can also try with proc_open, that allows you redirect the output to an arbitrary pipe.

Categories : PHP

Using python script to search in multiple files and outputting an individual file for each one
I think you keep getting confused between a single file and a list of files. Try something like this: def checkinitial(TD): #This counts the number of '.fits' files in your directory check = len(glob.glob1(TD,"*.fits")) if not check: print 'There are no .FITS files in this directory! Try Again...' sys.exit() return check def sorter(TD, targcheck, inicheck): """This function will call the two counters and compare them until the number of processed files is greater than the files in the directory, thereby finishing the loop """ for in_file in glob.iglob(os.path.join(TD,'*.fits')): print in_file # This prints out the filenames the program is currently processing with pyfits.open(in_file) as HDU: # <Process inpu

Categories : Python

Crontab Python Script Execution (Can't find settings config file)
Your code is looking for settings.cfg in its current working directory. This working directory will not be the same when cron executes the job, hence the error You have two "easy" solutions: Use an absolute path to the config file in your script (/home/tomi/amaer/config.cfg) CD to the appropriate directory first in your crontab (cd /home/tomi/amaer/ && python /home/tomi/amaer/controller.py) The "right" solution, though, would be to pass your script a parameter (or environment variable) that tells it where to look for the config file. It's not exactly good practice to assume your config file will always be lying just next to your script. You might want to have alook at this question: http://unix.stackexchange.com/questions/38951/what-is-the-working-directory-when-cron-exe

Categories : Python

speedup postgresql to add data from text file using Django python script
if you could express your requirements without the code (not every shell programmer can really read phython), possibly we could help here. e.g. your report of 12 hours for 15000 lines suggests you have a too-busy "for" loop somewhere, and i'd suggest the nested for for list in values[1].... what are you trying to strip? individual characters, whole words? ... then i'd suggest "awk".

Categories : Shell

how to call a python script inside another python script where both in the same directory?
In script1.py place this: def main(): do something if __name__ == "__main__": main() In script2.py: import script1 if condition: script1.main()

Categories : Python

Python script to create multiple users in a CSV file and generate email addresses
I'm basically guessing since you haven't said anything about what errors you're getting, but the most obvious problem I can see is that you're trying to add a string to a list of tuples, which doesn't make a lot of sense. 'Last_Name' [("@myemail.com")] should be: 'Last_Name' + "@myemail.com" Now, as far as what you're actually trying to do, which is extremely unclear, I think you want to use a series of list comprehensions. For example: users = [i for i in range(0, 10)] first_names = ["test"+str(user) for user in users] last_names = ["User%d" %user for user in users] email_addresses = [last_name + "@myemail.com" for last_name in last_names] passwords = ["Password1" for user in users] with open('mycsv.csv', 'wb') as csv_out: writer = csv.writer(csv_out) writer.writerows(zip(

Categories : Python

How to write a bash script that can parse through an XML file as input and remove certain elements from the file
Perhaps you could use php like this: running php script (php function) in linux bash And then you something like domdocument(http://php.net/manual/en/class.domdocument.php) to read and the right the xml. Of course this is assumes you have php installed.

Categories : Xml

Calling python script from C++ and using its output
Here is a solution to embed the execution of your python module from within your C++ application. It's not better or worst than forking/executing your python script through a system call, it just is a different way to do it. Whether it is best or not depend on your context and usage. Some time ago I have coded a way to load python modules as plugins to a C++ application, here's the interesting part. Basically, you need to #include <Python.h>, then Py_Initialize() to start your python interpreter. Then you do import sys, using : PyRun_SimpleString("import sys");, and you can load your plugin by doing PyRun_SimpleString('sys.path.append("path/to/my/module/")'). To exchange values between C++ and Python, things get harder, you have to to transform all your C++ objects into python o

Categories : C++

Python script runned through IDLE has no output
When you call a function, that function may return a value, and in this case os.getcwd() returns a string. Here, you never do anything to that string, so nothing happens - there's no output because you never print the string. For example, print os.getcwd() would output what you would expect. Reading your comment above, most Python interpreters will print out a representation of the return value of your code after it has been interpreted. This is why you see the string "printed" in the Python shell. However, when actually running the code, return values do not output.

Categories : Python

Converting Python RSA Decryption Script to C#, Output is only last 16B instead of 128B
The issue here is padding. RSA operations require that the message be padded with a secure padding scheme before encryption. Otherwise, certain attacks exist that could recover the private key. Here's a good article explaining why. For some reason, the Python crypto library is not removing the padding for you, but the C# library is. So you'll have to remove the padding manually in the Python code. Lucky for you, from the data you give, it looks like the padding scheme being used here is PKCS#1.5. That's a relatively simple padding scheme that will be easy to handle. The full specs are in RFC 3447, but it boils down to this: EM = 0x00 || 0x02 || PS || 0x00 || M. where EM is the padded message before encryption, PS is the padding, and M is the original, unpadded message. Here's a Pytho

Categories : C#

Trouble reading bash script output in Python
Can you try this one (I've used python 2.6.6, but may be you want it in the latest python 2.6): #!/usr/bin/python import subprocess import os CMD = "bin/findpid" p = subprocess.Popen(CMD, shell=True, stdout=subprocess.PIPE) print p.communicate()[0] UPDATE: probably, first grep of findpid script needs -v too?

Categories : Python

Get exit code from Python script with redirected output
Not a Korn-shell expert, but the pipefail solution from here should work in ksh, too. (And the separate execution one as well, obviously.)

Categories : Unix

custom output when control-c is used to exit python script
You could use try..except to catch KeyboardInterrupt: import time def main(): time.sleep(10) if __name__ == '__main__': try: main() except KeyboardInterrupt: print('bye')

Categories : Python



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.