Why won't program run? Learn Python 3 the Hard Way ex23 - macos

First off, I am a complete beginner with Python and I'm working my way through Zed Shaw's latest edition of Learn Python 3 the Hard Way. Im stuck on ex 23 String, Bytes, and Character Encoding. I can't get the program to run at all in the OSX terminal. When I attempt run the program it just returns zero information.
Here is a link to the screenshot of my terminal after I attempt to run the program.( Apparently i'm too much of a noob to embed my image lol.)
OSX python3.6 ex23.py
import sys
script, input_encoding, error = sys.argv
def main(language_file, encoding, errors):
line = language_file.readline()
if line:
print_line(line, encoding, errors)
return main(language_file, encoding, errors)
def print_line(line, encoding, errors):
next_lang = line.strip()
raw_bytes = next_lang.encode(encoding, errors=errors)
cooked_string = raw_bytes.decode(encoding, error=errors)
print(raw_bytes, "<===>", cooked_string)
languages = open("languages.txt", encoding="utf-8")
main(languages, input_encoding, error)
Why is this not running? What's going on?

Are you sure it is not just incorrect indentation? Python uses indentation instead of braces to structure its programs. Looking at your code, it seems that you have extra indentations, try this:
import sys
script, input_encoding, error = sys.argv
def main(language_file, encoding, errors):
line = language_file.readline()
if line:
print_line(line, encoding, errors)
return main(language_file, encoding, errors)
def print_line(line, encoding, errors):
next_lang = line.strip()
raw_bytes = next_lang.encode(encoding, errors=errors)
cooked_string = raw_bytes.decode(encoding, errors=errors)
print(raw_bytes, "<===>", cooked_string)
languages = open("languages.txt", encoding="utf-8")
main(languages, input_encoding, error)

Related

Bash Script - Not collateral after echo due to new line [duplicate]

I want to write a function that will execute a shell command and return its output as a string, no matter, is it an error or success message. I just want to get the same result that I would have gotten with the command line.
What would be a code example that would do such a thing?
For example:
def run_command(cmd):
# ??????
print run_command('mysqladmin create test -uroot -pmysqladmin12')
# Should output something like:
# mysqladmin: CREATE DATABASE failed; error: 'Can't create database 'test'; database exists'
In all officially maintained versions of Python, the simplest approach is to use the subprocess.check_output function:
>>> subprocess.check_output(['ls', '-l'])
b'total 0\n-rw-r--r-- 1 memyself staff 0 Mar 14 11:04 files\n'
check_output runs a single program that takes only arguments as input.1 It returns the result exactly as printed to stdout. If you need to write input to stdin, skip ahead to the run or Popen sections. If you want to execute complex shell commands, see the note on shell=True at the end of this answer.
The check_output function works in all officially maintained versions of Python. But for more recent versions, a more flexible approach is available.
Modern versions of Python (3.5 or higher): run
If you're using Python 3.5+, and do not need backwards compatibility, the new run function is recommended by the official documentation for most tasks. It provides a very general, high-level API for the subprocess module. To capture the output of a program, pass the subprocess.PIPE flag to the stdout keyword argument. Then access the stdout attribute of the returned CompletedProcess object:
>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r-- 1 memyself staff 0 Mar 14 11:04 files\n'
The return value is a bytes object, so if you want a proper string, you'll need to decode it. Assuming the called process returns a UTF-8-encoded string:
>>> result.stdout.decode('utf-8')
'total 0\n-rw-r--r-- 1 memyself staff 0 Mar 14 11:04 files\n'
This can all be compressed to a one-liner if desired:
>>> subprocess.run(['ls', '-l'], stdout=subprocess.PIPE).stdout.decode('utf-8')
'total 0\n-rw-r--r-- 1 memyself staff 0 Mar 14 11:04 files\n'
If you want to pass input to the process's stdin, you can pass a bytes object to the input keyword argument:
>>> cmd = ['awk', 'length($0) > 5']
>>> ip = 'foo\nfoofoo\n'.encode('utf-8')
>>> result = subprocess.run(cmd, stdout=subprocess.PIPE, input=ip)
>>> result.stdout.decode('utf-8')
'foofoo\n'
You can capture errors by passing stderr=subprocess.PIPE (capture to result.stderr) or stderr=subprocess.STDOUT (capture to result.stdout along with regular output). If you want run to throw an exception when the process returns a nonzero exit code, you can pass check=True. (Or you can check the returncode attribute of result above.) When security is not a concern, you can also run more complex shell commands by passing shell=True as described at the end of this answer.
Later versions of Python streamline the above further. In Python 3.7+, the above one-liner can be spelled like this:
>>> subprocess.run(['ls', '-l'], capture_output=True, text=True).stdout
'total 0\n-rw-r--r-- 1 memyself staff 0 Mar 14 11:04 files\n'
Using run this way adds just a bit of complexity, compared to the old way of doing things. But now you can do almost anything you need to do with the run function alone.
Older versions of Python (3-3.4): more about check_output
If you are using an older version of Python, or need modest backwards compatibility, you can use the check_output function as briefly described above. It has been available since Python 2.7.
subprocess.check_output(*popenargs, **kwargs)
It takes takes the same arguments as Popen (see below), and returns a string containing the program's output. The beginning of this answer has a more detailed usage example. In Python 3.5+, check_output is equivalent to executing run with check=True and stdout=PIPE, and returning just the stdout attribute.
You can pass stderr=subprocess.STDOUT to ensure that error messages are included in the returned output. When security is not a concern, you can also run more complex shell commands by passing shell=True as described at the end of this answer.
If you need to pipe from stderr or pass input to the process, check_output won't be up to the task. See the Popen examples below in that case.
Complex applications and legacy versions of Python (2.6 and below): Popen
If you need deep backwards compatibility, or if you need more sophisticated functionality than check_output or run provide, you'll have to work directly with Popen objects, which encapsulate the low-level API for subprocesses.
The Popen constructor accepts either a single command without arguments, or a list containing a command as its first item, followed by any number of arguments, each as a separate item in the list. shlex.split can help parse strings into appropriately formatted lists. Popen objects also accept a host of different arguments for process IO management and low-level configuration.
To send input and capture output, communicate is almost always the preferred method. As in:
output = subprocess.Popen(["mycmd", "myarg"],
stdout=subprocess.PIPE).communicate()[0]
Or
>>> import subprocess
>>> p = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE,
... stderr=subprocess.PIPE)
>>> out, err = p.communicate()
>>> print out
.
..
foo
If you set stdin=PIPE, communicate also allows you to pass data to the process via stdin:
>>> cmd = ['awk', 'length($0) > 5']
>>> p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
... stderr=subprocess.PIPE,
... stdin=subprocess.PIPE)
>>> out, err = p.communicate('foo\nfoofoo\n')
>>> print out
foofoo
Note Aaron Hall's answer, which indicates that on some systems, you may need to set stdout, stderr, and stdin all to PIPE (or DEVNULL) to get communicate to work at all.
In some rare cases, you may need complex, real-time output capturing. Vartec's answer suggests a way forward, but methods other than communicate are prone to deadlocks if not used carefully.
As with all the above functions, when security is not a concern, you can run more complex shell commands by passing shell=True.
Notes
1. Running shell commands: the shell=True argument
Normally, each call to run, check_output, or the Popen constructor executes a single program. That means no fancy bash-style pipes. If you want to run complex shell commands, you can pass shell=True, which all three functions support. For example:
>>> subprocess.check_output('cat books/* | wc', shell=True, text=True)
' 1299377 17005208 101299376\n'
However, doing this raises security concerns. If you're doing anything more than light scripting, you might be better off calling each process separately, and passing the output from each as an input to the next, via
run(cmd, [stdout=etc...], input=other_output)
Or
Popen(cmd, [stdout=etc...]).communicate(other_output)
The temptation to directly connect pipes is strong; resist it. Otherwise, you'll likely see deadlocks or have to do hacky things like this.
This is way easier, but only works on Unix (including Cygwin) and Python2.7.
import commands
print commands.getstatusoutput('wc -l file')
It returns a tuple with the (return_value, output).
For a solution that works in both Python2 and Python3, use the subprocess module instead:
from subprocess import Popen, PIPE
output = Popen(["date"],stdout=PIPE)
response = output.communicate()
print response
I had the same problem but figured out a very simple way of doing this:
import subprocess
output = subprocess.getoutput("ls -l")
print(output)
Note: This solution is Python3 specific as subprocess.getoutput() doesn't work in Python2
Something like that:
def runProcess(exe):
p = subprocess.Popen(exe, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while(True):
# returns None while subprocess is running
retcode = p.poll()
line = p.stdout.readline()
yield line
if retcode is not None:
break
Note, that I'm redirecting stderr to stdout, it might not be exactly what you want, but I want error messages also.
This function yields line by line as they come (normally you'd have to wait for subprocess to finish to get the output as a whole).
For your case the usage would be:
for line in runProcess('mysqladmin create test -uroot -pmysqladmin12'.split()):
print line,
This is a tricky but super simple solution which works in many situations:
import os
os.system('sample_cmd > tmp')
print(open('tmp', 'r').read())
A temporary file(here is tmp) is created with the output of the command and you can read from it your desired output.
Extra note from the comments:
You can remove the tmp file in the case of one-time job. If you need to do this several times, there is no need to delete the tmp.
os.remove('tmp')
Vartec's answer doesn't read all lines, so I made a version that did:
def run_command(command):
p = subprocess.Popen(command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
return iter(p.stdout.readline, b'')
Usage is the same as the accepted answer:
command = 'mysqladmin create test -uroot -pmysqladmin12'.split()
for line in run_command(command):
print(line)
You can use following commands to run any shell command. I have used them on ubuntu.
import os
os.popen('your command here').read()
Note: This is deprecated since python 2.6. Now you must use subprocess.Popen. Below is the example
import subprocess
p = subprocess.Popen("Your command", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0]
print p.split("\n")
I had a slightly different flavor of the same problem with the following requirements:
Capture and return STDOUT messages as they accumulate in the STDOUT buffer (i.e. in realtime).
#vartec solved this Pythonically with his use of generators and the 'yield'
keyword above
Print all STDOUT lines (even if process exits before STDOUT buffer can be fully read)
Don't waste CPU cycles polling the process at high-frequency
Check the return code of the subprocess
Print STDERR (separate from STDOUT) if we get a non-zero error return code.
I've combined and tweaked previous answers to come up with the following:
import subprocess
from time import sleep
def run_command(command):
p = subprocess.Popen(command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
# Read stdout from subprocess until the buffer is empty !
for line in iter(p.stdout.readline, b''):
if line: # Don't print blank lines
yield line
# This ensures the process has completed, AND sets the 'returncode' attr
while p.poll() is None:
sleep(.1) #Don't waste CPU-cycles
# Empty STDERR buffer
err = p.stderr.read()
if p.returncode != 0:
# The run_command() function is responsible for logging STDERR
print("Error: " + str(err))
This code would be executed the same as previous answers:
for line in run_command(cmd):
print(line)
Your Mileage May Vary, I attempted #senderle's spin on Vartec's solution in Windows on Python 2.6.5, but I was getting errors, and no other solutions worked. My error was: WindowsError: [Error 6] The handle is invalid.
I found that I had to assign PIPE to every handle to get it to return the output I expected - the following worked for me.
import subprocess
def run_command(cmd):
"""given shell command, returns communication tuple of stdout and stderr"""
return subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE).communicate()
and call like this, ([0] gets the first element of the tuple, stdout):
run_command('tracert 11.1.0.1')[0]
After learning more, I believe I need these pipe arguments because I'm working on a custom system that uses different handles, so I had to directly control all the std's.
To stop console popups (with Windows), do this:
def run_command(cmd):
"""given shell command, returns communication tuple of stdout and stderr"""
# instantiate a startupinfo obj:
startupinfo = subprocess.STARTUPINFO()
# set the use show window flag, might make conditional on being in Windows:
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
# pass as the startupinfo keyword argument:
return subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE,
startupinfo=startupinfo).communicate()
run_command('tracert 11.1.0.1')
On Python 3.7+, use subprocess.run and pass capture_output=True:
import subprocess
result = subprocess.run(['echo', 'hello', 'world'], capture_output=True)
print(repr(result.stdout))
This will return bytes:
b'hello world\n'
If you want it to convert the bytes to a string, add text=True:
result = subprocess.run(['echo', 'hello', 'world'], capture_output=True, text=True)
print(repr(result.stdout))
This will read the bytes using your default encoding:
'hello world\n'
If you need to manually specify a different encoding, use encoding="your encoding" instead of text=True:
result = subprocess.run(['echo', 'hello', 'world'], capture_output=True, encoding="utf8")
print(repr(result.stdout))
Splitting the initial command for the subprocess might be tricky and cumbersome.
Use shlex.split() to help yourself out.
Sample command
git log -n 5 --since "5 years ago" --until "2 year ago"
The code
from subprocess import check_output
from shlex import split
res = check_output(split('git log -n 5 --since "5 years ago" --until "2 year ago"'))
print(res)
>>> b'commit 7696ab087a163e084d6870bb4e5e4d4198bdc61a\nAuthor: Artur Barseghyan...'
Without shlex.split() the code would look as follows
res = check_output([
'git',
'log',
'-n',
'5',
'--since',
'5 years ago',
'--until',
'2 year ago'
])
print(res)
>>> b'commit 7696ab087a163e084d6870bb4e5e4d4198bdc61a\nAuthor: Artur Barseghyan...'
Here a solution, working if you want to print output while process is running or not.
I added the current working directory also, it was useful to me more than once.
Hoping the solution will help someone :).
import subprocess
def run_command(cmd_and_args, print_constantly=False, cwd=None):
"""Runs a system command.
:param cmd_and_args: the command to run with or without a Pipe (|).
:param print_constantly: If True then the output is logged in continuous until the command ended.
:param cwd: the current working directory (the directory from which you will like to execute the command)
:return: - a tuple containing the return code, the stdout and the stderr of the command
"""
output = []
process = subprocess.Popen(cmd_and_args, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd)
while True:
next_line = process.stdout.readline()
if next_line:
output.append(str(next_line))
if print_constantly:
print(next_line)
elif not process.poll():
break
error = process.communicate()[1]
return process.returncode, '\n'.join(output), error
For some reason, this one works on Python 2.7 and you only need to import os!
import os
def bash(command):
output = os.popen(command).read()
return output
print_me = bash('ls -l')
print(print_me)
If you need to run a shell command on multiple files, this did the trick for me.
import os
import subprocess
# Define a function for running commands and capturing stdout line by line
# (Modified from Vartec's solution because it wasn't printing all lines)
def runProcess(exe):
p = subprocess.Popen(exe, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
return iter(p.stdout.readline, b'')
# Get all filenames in working directory
for filename in os.listdir('./'):
# This command will be run on each file
cmd = 'nm ' + filename
# Run the command and capture the output line by line.
for line in runProcess(cmd.split()):
# Eliminate leading and trailing whitespace
line.strip()
# Split the output
output = line.split()
# Filter the output and print relevant lines
if len(output) > 2:
if ((output[2] == 'set_program_name')):
print filename
print line
Edit: Just saw Max Persson's solution with J.F. Sebastian's suggestion. Went ahead and incorporated that.
According to #senderle, if you use python3.6 like me:
def sh(cmd, input=""):
rst = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, input=input.encode("utf-8"))
assert rst.returncode == 0, rst.stderr.decode("utf-8")
return rst.stdout.decode("utf-8")
sh("ls -a")
Will act exactly like you run the command in bash
Improvement for better logging.
For better output you can use iterator.
From below, we get better
from subprocess import Popen, getstatusoutput, PIPE
def shell_command(cmd):
result = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
output = iter(result.stdout.readline, b'')
error = iter(result.stderr.readline, b'')
print("##### OutPut ###")
for line in output:
print(line.decode("utf-8"))
print("###### Error ########")
for line in error:
print(error.decode("utf-8")) # Convert bytes to str
status, terminal_output = run_command(cmd)
print(terminal_output)
shell_command("ls") # this will display all the files & folders in directory
Other method using getstatusoutput ( Easy to understand)
from subprocess import Popen, getstatusoutput, PIPE
status_Code, output = getstausoutput(command)
print(output) # this will give the terminal output
# status_code, output = getstatusoutput("ls") # this will print the all files & folder available in the directory
If you use the subprocess python module, you are able to handle the STDOUT, STDERR and return code of command separately. You can see an example for the complete command caller implementation. Of course you can extend it with try..except if you want.
The below function returns the STDOUT, STDERR and Return code so you can handle them in the other script.
import subprocess
def command_caller(command=None)
sp = subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=False)
out, err = sp.communicate()
if sp.returncode:
print(
"Return code: %(ret_code)s Error message: %(err_msg)s"
% {"ret_code": sp.returncode, "err_msg": err}
)
return sp.returncode, out, err
I would like to suggest simppl as an option for consideration. It is a module that is available via pypi: pip install simppl and was runs on python3.
simppl allows the user to run shell commands and read the output from the screen.
The developers suggest three types of use cases:
The simplest usage will look like this:
from simppl.simple_pipeline import SimplePipeline
sp = SimplePipeline(start=0, end=100):
sp.print_and_run('<YOUR_FIRST_OS_COMMAND>')
sp.print_and_run('<YOUR_SECOND_OS_COMMAND>') ```
To run multiple commands concurrently use:
commands = ['<YOUR_FIRST_OS_COMMAND>', '<YOUR_SECOND_OS_COMMAND>']
max_number_of_processes = 4
sp.run_parallel(commands, max_number_of_processes) ```
Finally, if your project uses the cli module, you can run directly another command_line_tool as part of a pipeline. The other tool will
be run from the same process, but it will appear from the logs as
another command in the pipeline. This enables smoother debugging and
refactoring of tools calling other tools.
from example_module import example_tool
sp.print_and_run_clt(example_tool.run, ['first_number', 'second_nmber'],
{'-key1': 'val1', '-key2': 'val2'},
{'--flag'}) ```
Note that the printing to STDOUT/STDERR is via python's logging module.
Here is a complete code to show how simppl works:
import logging
from logging.config import dictConfig
logging_config = dict(
version = 1,
formatters = {
'f': {'format':
'%(asctime)s %(name)-12s %(levelname)-8s %(message)s'}
},
handlers = {
'h': {'class': 'logging.StreamHandler',
'formatter': 'f',
'level': logging.DEBUG}
},
root = {
'handlers': ['h'],
'level': logging.DEBUG,
},
)
dictConfig(logging_config)
from simppl.simple_pipeline import SimplePipeline
sp = SimplePipeline(0, 100)
sp.print_and_run('ls')
Here is a simple and flexible solution that works on a variety of OS versions, and both Python 2 and 3, using IPython in shell mode:
from IPython.terminal.embed import InteractiveShellEmbed
my_shell = InteractiveShellEmbed()
result = my_shell.getoutput("echo hello world")
print(result)
Out: ['hello world']
It has a couple of advantages
It only requires an IPython install, so you don't really need to worry about your specific Python or OS version when using it, it comes with Jupyter - which has a wide range of support
It takes a simple string by default - so no need to use shell mode arg or string splitting, making it slightly cleaner IMO
It also makes it cleaner to easily substitute variables or even entire Python commands in the string itself
To demonstrate:
var = "hello world "
result = my_shell.getoutput("echo {var*2}")
print(result)
Out: ['hello world hello world']
Just wanted to give you an extra option, especially if you already have Jupyter installed
Naturally, if you are in an actual Jupyter notebook as opposed to a .py script you can also always do:
result = !echo hello world
print(result)
To accomplish the same.
The output can be redirected to a text file and then read it back.
import subprocess
import os
import tempfile
def execute_to_file(command):
"""
This function execute the command
and pass its output to a tempfile then read it back
It is usefull for process that deploy child process
"""
temp_file = tempfile.NamedTemporaryFile(delete=False)
temp_file.close()
path = temp_file.name
command = command + " > " + path
proc = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
if proc.stderr:
# if command failed return
os.unlink(path)
return
with open(path, 'r') as f:
data = f.read()
os.unlink(path)
return data
if __name__ == "__main__":
path = "Somepath"
command = 'ecls.exe /files ' + path
print(execute(command))
eg, execute('ls -ahl')
differentiated three/four possible returns and OS platforms:
no output, but run successfully
output empty line, run successfully
run failed
output something, run successfully
function below
def execute(cmd, output=True, DEBUG_MODE=False):
"""Executes a bash command.
(cmd, output=True)
output: whether print shell output to screen, only affects screen display, does not affect returned values
return: ...regardless of output=True/False...
returns shell output as a list with each elment is a line of string (whitespace stripped both sides) from output
could be
[], ie, len()=0 --> no output;
[''] --> output empty line;
None --> error occured, see below
if error ocurs, returns None (ie, is None), print out the error message to screen
"""
if not DEBUG_MODE:
print "Command: " + cmd
# https://stackoverflow.com/a/40139101/2292993
def _execute_cmd(cmd):
if os.name == 'nt' or platform.system() == 'Windows':
# set stdin, out, err all to PIPE to get results (other than None) after run the Popen() instance
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
else:
# Use bash; the default is sh
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, executable="/bin/bash")
# the Popen() instance starts running once instantiated (??)
# additionally, communicate(), or poll() and wait process to terminate
# communicate() accepts optional input as stdin to the pipe (requires setting stdin=subprocess.PIPE above), return out, err as tuple
# if communicate(), the results are buffered in memory
# Read stdout from subprocess until the buffer is empty !
# if error occurs, the stdout is '', which means the below loop is essentially skipped
# A prefix of 'b' or 'B' is ignored in Python 2;
# it indicates that the literal should become a bytes literal in Python 3
# (e.g. when code is automatically converted with 2to3).
# return iter(p.stdout.readline, b'')
for line in iter(p.stdout.readline, b''):
# # Windows has \r\n, Unix has \n, Old mac has \r
# if line not in ['','\n','\r','\r\n']: # Don't print blank lines
yield line
while p.poll() is None:
sleep(.1) #Don't waste CPU-cycles
# Empty STDERR buffer
err = p.stderr.read()
if p.returncode != 0:
# responsible for logging STDERR
print("Error: " + str(err))
yield None
out = []
for line in _execute_cmd(cmd):
# error did not occur earlier
if line is not None:
# trailing comma to avoid a newline (by print itself) being printed
if output: print line,
out.append(line.strip())
else:
# error occured earlier
out = None
return out
else:
print "Simulation! The command is " + cmd
print ""

Why is the output file from Biopython not found?

I work with a Mac. I have been trying to make a multiple sequence alignment in Python using Muscle. This is the code I have been running:
from Bio.Align.Applications import MuscleCommandline
cline = MuscleCommandline(input="testunaligned.fasta", out="testunaligned.aln", clwstrict=True)
print(cline)
from Bio import AlignIO
align = AlignIO.read(open("testunaligned.aln"), "clustal")
print(align)
I keep getting the following error:
FileNotFoundError: [Errno 2] No such file or directory: 'testunaligned.aln'
Does anyone know how I could fix this? I am very new to Python and computer science in general, and I am totally at a loss. Thanks!
cline in your code is an instance of MuscleCommandline object that you initialized with all the parameters. After the initialization, this instance can run muscle, but it will only do that if you call it. That means you have to invoke cline()
When you simply print the cline object, it will return a string that corresponds to the command you can manually run on the command line to get the same result as when you invoke cline().
And here the working code:
from Bio.Align.Applications import MuscleCommandline
cline = MuscleCommandline(
input="testunaligned.fasta",
out="testunaligned.aln",
clwstrict=True
)
print(cline)
cline() # this is where mucle runs
from Bio import AlignIO
align = AlignIO.read(open("testunaligned.aln"), "clustal")
print(align)

Workaround for Scala Error: The command line is too long?

I'm trying to compile someone's mod of minecraft so that I can make some changes to it. It uses scala somewhere in the recompiling, and I get this error:
== ERRORS FOUND in SCALA CODE ==
The command line is too long.
================================
I tend to agree:
'"scalac.bat" -encoding UTF-8 -deprecation -target:jvm-1.6 -classpath "jars\vers
ions\1.8.1\1.8.1.jar;lib;lib\*;lib;lib\*;jars\bin\minecraft.jar;jars\bin\jinput.
jar;jars\bin\lwjgl.jar;jars\bin\lwjgl_util.jar;jars\libraries\net\java\jinput\ji
nput\2.0.5\jinput-2.0.5.jar;jars\libraries\org\lwjgl\lwjgl\lwjgl-platform\2.9.1\
lwjgl-platform-2.9.1-natives-windows.jar;jars\libraries\com\ibm\icu\icu4j-core-m
ojang\51.2\icu4j-core-mojang-51.2.jar;jars\libraries\tv\twitch\twitch-external-p
latform\4.5\twitch-external-platform-4.5-natives-windows-64.jar;jars\libraries\c
om\sixense\SixenseJavaLibrary\062612.0\SixenseJavaLibrary-062612.0-natives-windo
ws.jar;jars\libraries\org\apache\httpcomponents\httpcore\4.3.2\httpcore-4.3.2.ja
r;jars\libraries\org\apache\logging\log4j\log4j-api\2.0-beta9\log4j-api-2.0-beta
9.jar;jars\libraries\org\apache\commons\commons-lang3\3.3.2\commons-lang3-3.3.2.
jar;jars\libraries\net\java\jutils\jutils\1.0.0\jutils-1.0.0.jar;jars\libraries\
com\paulscode\libraryjavasound\20101123\libraryjavasound-20101123.jar;jars\libra
ries\net\sf\jopt-simple\jopt-simple\4.6\jopt-simple-4.6.jar;jars\libraries\com\g
oogle\guava\guava\17.0\guava-17.0.jar;jars\libraries\commons-logging\commons-log
ging\1.1.3\commons-logging-1.1.3.jar;jars\libraries\org\apache\commons\commons-c
ompress\1.8.1\commons-compress-1.8.1.jar;jars\libraries\com\sixense\SixenseJava\
062612.1\SixenseJava-062612.1.jar;jars\libraries\tv\twitch\twitch\6.5\twitch-6.5
.jar;jars\libraries\com\paulscode\codecjorbis\20101023\codecjorbis-20101023.jar;
jars\libraries\optifine\OptiFine\1.8.1_HD_U_B2\OptiFine-1.8.1_HD_U_B2.jar;jars\l
ibraries\com\paulscode\soundsystem\20120107\soundsystem-20120107.jar;jars\librar
ies\org\json\json\20140107\json-20140107.jar;jars\libraries\com\paulscode\librar
ylwjglopenal\20100824\librarylwjglopenal-20100824.jar;jars\libraries\org\lwjgl\l
wjgl\lwjgl_util\2.9.1\lwjgl_util-2.9.1.jar;jars\libraries\commons-codec\commons-
codec\1.9\commons-codec-1.9.jar;jars\libraries\org\apache\httpcomponents\httpcli
ent\4.3.3\httpclient-4.3.3.jar;jars\libraries\de\fruitfly\ovr\JRiftLibrary\0.4.4
.1\JRiftLibrary-0.4.4.1-natives-windows.jar;jars\libraries\org\lwjgl\lwjgl\lwjgl
\2.9.1\lwjgl-2.9.1.jar;jars\libraries\commons-io\commons-io\2.4\commons-io-2.4.j
ar;jars\libraries\com\mojang\realms\1.7.4\realms-1.7.4.jar;jars\libraries\net\ai
b42\mumblelink\JMumbleLibrary\1.1\JMumbleLibrary-1.1-natives-windows.jar;jars\li
braries\com\mojang\authlib\1.5.17\authlib-1.5.17.jar;jars\libraries\com\google\c
ode\gson\gson\2.2.4\gson-2.2.4.jar;jars\libraries\net\minecraft\launchwrapper\1.
7\launchwrapper-1.7.jar;jars\libraries\com\paulscode\codecwav\20101023\codecwav-
20101023.jar;jars\libraries\tv\twitch\twitch-platform\6.5\twitch-platform-6.5-na
tives-windows-64.jar;jars\libraries\net\java\jinput\jinput-platform\2.0.5\jinput
-platform-2.0.5-natives-windows.jar;jars\libraries\de\fruitfly\ovr\JRift\0.4.4.1
\JRift-0.4.4.1.jar;jars\libraries\org\apache\logging\log4j\log4j-core\2.0-beta9\
log4j-core-2.0-beta9.jar;jars\libraries\net\aib42\mumblelink\JMumble\1.0\JMumble
-1.0.jar;jars\libraries\io\netty\netty-all\4.0.23.Final\netty-all-4.0.23.Final.j
ar" -sourcepath src\minecraft -d bin\minecraft src\minecraft\*.java src\minecraf
t\net\minecraft\block\*.java src\minecraft\net\minecraft\block\material\*.java s
rc\minecraft\net\minecraft\block\properties\*.java src\minecraft\net\minecraft\b
lock\state\*.java src\minecraft\net\minecraft\block\state\pattern\*.java src\min
ecraft\net\minecraft\client\*.java src\minecraft\net\minecraft\client\audio\*.ja
va src\minecraft\net\minecraft\client\entity\*.java src\minecraft\net\minecraft\
client\gui\*.java src\minecraft\net\minecraft\client\gui\achievement\*.java src\
minecraft\net\minecraft\client\gui\inventory\*.java src\minecraft\net\minecraft\
client\gui\spectator\*.java src\minecraft\net\minecraft\client\gui\spectator\cat
egories\*.java src\minecraft\net\minecraft\client\gui\stream\*.java src\minecraf
t\net\minecraft\client\main\*.java src\minecraft\net\minecraft\client\model\*.ja
va src\minecraft\net\minecraft\client\multiplayer\*.java src\minecraft\net\minec
raft\client\network\*.java src\minecraft\net\minecraft\client\particle\*.java sr
c\minecraft\net\minecraft\client\player\inventory\*.java src\minecraft\net\minec
raft\client\renderer\*.java src\minecraft\net\minecraft\client\renderer\block\mo
del\*.java src\minecraft\net\minecraft\client\renderer\block\statemap\*.java src
\minecraft\net\minecraft\client\renderer\chunk\*.java src\minecraft\net\minecraf
t\client\renderer\culling\*.java src\minecraft\net\minecraft\client\renderer\ent
ity\*.java src\minecraft\net\minecraft\client\renderer\entity\layers\*.java src\
minecraft\net\minecraft\client\renderer\texture\*.java src\minecraft\net\minecra
ft\client\renderer\tileentity\*.java src\minecraft\net\minecraft\client\renderer
\vertex\*.java src\minecraft\net\minecraft\client\resources\*.java src\minecraft
\net\minecraft\client\resources\data\*.java src\minecraft\net\minecraft\client\r
esources\model\*.java src\minecraft\net\minecraft\client\settings\*.java src\min
ecraft\net\minecraft\client\shader\*.java src\minecraft\net\minecraft\client\str
eam\*.java src\minecraft\net\minecraft\client\util\*.java src\minecraft\net\mine
craft\command\*.java src\minecraft\net\minecraft\command\common\*.java src\minec
raft\net\minecraft\command\server\*.java src\minecraft\net\minecraft\crash\*.jav
a src\minecraft\net\minecraft\creativetab\*.java src\minecraft\net\minecraft\dis
penser\*.java src\minecraft\net\minecraft\enchantment\*.java src\minecraft\net\m
inecraft\entity\*.java src\minecraft\net\minecraft\entity\ai\*.java src\minecraf
t\net\minecraft\entity\ai\attributes\*.java src\minecraft\net\minecraft\entity\b
oss\*.java src\minecraft\net\minecraft\entity\effect\*.java src\minecraft\net\mi
necraft\entity\item\*.java src\minecraft\net\minecraft\entity\monster\*.java src
\minecraft\net\minecraft\entity\passive\*.java src\minecraft\net\minecraft\entit
y\player\*.java src\minecraft\net\minecraft\entity\projectile\*.java src\minecra
ft\net\minecraft\event\*.java src\minecraft\net\minecraft\init\*.java src\minecr
aft\net\minecraft\inventory\*.java src\minecraft\net\minecraft\item\*.java src\m
inecraft\net\minecraft\item\crafting\*.java src\minecraft\net\minecraft\nbt\*.ja
va src\minecraft\net\minecraft\network\*.java src\minecraft\net\minecraft\networ
k\handshake\*.java src\minecraft\net\minecraft\network\handshake\client\*.java s
rc\minecraft\net\minecraft\network\login\*.java src\minecraft\net\minecraft\netw
ork\login\client\*.java src\minecraft\net\minecraft\network\login\server\*.java
src\minecraft\net\minecraft\network\play\*.java src\minecraft\net\minecraft\netw
ork\play\client\*.java src\minecraft\net\minecraft\network\play\server\*.java sr
c\minecraft\net\minecraft\network\status\*.java src\minecraft\net\minecraft\netw
ork\status\client\*.java src\minecraft\net\minecraft\network\status\server\*.jav
a src\minecraft\net\minecraft\pathfinding\*.java src\minecraft\net\minecraft\pot
ion\*.java src\minecraft\net\minecraft\profiler\*.java src\minecraft\net\minecra
ft\realms\*.java src\minecraft\net\minecraft\scoreboard\*.java src\minecraft\net
\minecraft\server\*.java src\minecraft\net\minecraft\server\gui\*.java src\minec
raft\net\minecraft\server\integrated\*.java src\minecraft\net\minecraft\server\m
anagement\*.java src\minecraft\net\minecraft\server\network\*.java src\minecraft
\net\minecraft\src\*.java src\minecraft\net\minecraft\stats\*.java src\minecraft
\net\minecraft\tileentity\*.java src\minecraft\net\minecraft\util\*.java src\min
ecraft\net\minecraft\village\*.java src\minecraft\net\minecraft\world\*.java src
\minecraft\net\minecraft\world\biome\*.java src\minecraft\net\minecraft\world\bo
rder\*.java src\minecraft\net\minecraft\world\chunk\*.java src\minecraft\net\min
ecraft\world\chunk\storage\*.java src\minecraft\net\minecraft\world\demo\*.java
src\minecraft\net\minecraft\world\gen\*.java src\minecraft\net\minecraft\world\g
en\feature\*.java src\minecraft\net\minecraft\world\gen\layer\*.java src\minecra
ft\net\minecraft\world\gen\structure\*.java src\minecraft\net\minecraft\world\pa
thfinder\*.java src\minecraft\net\minecraft\world\storage\*.java src\minecraft\o
ptifine\*.java src\minecraft\optifine\json\*.java' failed : 1
Given that windows has a character limit on the command line.
I'm using windows 8.1 and scala 2.11.0.
I was wondering, is there a way to set this as an environment/path variable or something to avoid this?
What would I have to change? I'm very new to messing around with system stuff like this, but I think I know where scala is called in the scripts and this argument is given. If that helps.
scalac accepts an #file parameter containing a file with arguments in. So if you can modify whatever script is calling scalac.bat to instead put the arguments in a temporary file arguments.txt and then call scalac #arguments.txt that should work.

Insert Unicode symbol in Geany at cursor position

I want to insert certain Unicode symbol at current cursor position when Control-L is pressed. How to achieve this in Geany? (symbol ロ for example)
Had a similar desire. Here is a solution that makes use of the GeanyPy plugin:
Install and enable GeanyPy plugin that allows you to write Python plugins for Geany (this is available as geany-plugin-py in Ubuntu 16.04).
Place the following in your plugin directory (for me this was ~/.config/geany/plugins/):
# -*- coding: utf-8 -*-
import gtk
import geany
class InsertSymbols(geany.Plugin):
__plugin_name__ = "InsertSymbols"
__plugin_version__ = "0.1"
__plugin_description__ = "Insert symbols e.g. unicode"
__plugin_author__ = "klimaat"
chars = ['°', '×', '²', '³', '±', 'µ', '·', 'ロ']
def __init__(self):
self.symbol_menuitem = gtk.MenuItem("Insert Symbol")
self.symbol_menuitem.show()
symbol_submenu = gtk.Menu()
self.symbol_menuitem.set_submenu(symbol_submenu)
for char in self.chars:
char_item = gtk.MenuItem(char)
char_item.show()
char_item.connect("activate", self.on_insert_symbol_clicked)
symbol_submenu.append(char_item)
geany.main_widgets.tools_menu.append(self.symbol_menuitem)
def cleanup(self):
self.symbol_menuitem.destroy()
def on_insert_symbol_clicked(self, data):
char = data.get_label()
doc = geany.document.get_current()
if doc:
pos = doc.editor.scintilla.get_current_position()
doc.editor.scintilla.insert_text(char)
doc.editor.scintilla.set_current_position(pos+2)
You should now have a "Insert Symbol" item under "Tools".
Probably much better ways to do it...
Macros Plugin helped. It allows to assign a Control-L key, and it has a command to insert any text at cursor. Took some time to figure, but not difficult.

Best Way of redirecting output to a VTE terminal

Which is the best way of redirect the output of a command to a VTE terminal?
i came with this idea:
On the VTE execute:
tty > /usr/tmp/terminal_number
then read the file from the python program:
with open('/usr/tmp/terminal_number', 'r') as f:
self.VTE_redirect_path=f.readline()
then execute the bash commands, for exemple:
os.system('''echo "foo" > {0}'''.format(self.VTE_redirect_path))
The problem of this method is that the file terminal_number containing /dev/pts/# needs to be refreshed. Also i don't really like the idea of having to create files to communicate. Is there any direct solution?
#Quentin The solution that you gave me prints the console output really bad (it doesn't indents) so i had to use my solution. Here is a clear example:
from gi.repository import Gtk, GObject, Vte, GLib
import os, time, threading
def command_on_VTE(self,command):
length=len(command)
self.terminal.feed_child(command, length)
class TheWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="inherited cell renderer")
self.set_default_size(600, 300)
self.terminal=Vte.Terminal()
self.terminal.fork_command_full(
Vte.PtyFlags.DEFAULT, #default is fine
os.environ['HOME'], #where to start the command?
["/bin/bash"], #where is the emulator?
[], #it's ok to leave this list empty
GLib.SpawnFlags.DO_NOT_REAP_CHILD,
None, #at least None is required
None,
)
#set up the interface
box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
#a scroll window is required for the terminal
scroller = Gtk.ScrolledWindow()
scroller.set_hexpand(True)
scroller.set_vexpand(True)
scroller.add(self.terminal)
box.pack_start(scroller, False, True, 2)
self.add(box)
#To get the command to automatically run
#a newline(\n) character is used at the end of the
#command string.
command_on_VTE(self,'''tty > /tmp/terminal_number\n''') # Get the terminal ID
# read the terminal ID
while not os.path.exists("/tmp/terminal_number"):
time.sleep(0.1)
with open('/tmp/terminal_number', 'r') as f:
self.VTE_redirect_path=f.readline()
os.remove('/tmp/terminal_number')
# this cleans the vte
os.system('''printf "\\033c" > {0}'''.format(self.VTE_redirect_path))
# this calls the exemple
threading.Thread(target=self.make_a_test).start()
def make_a_test(self):
os.system('''ls -laR /home/ > {rdc}
echo "-------- The listing ended -------
Note that the input of the commands are not printed
" > {rdc}'''.format(rdc=self.VTE_redirect_path))
win = TheWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()
I haven't found a way of getting the Terminal ID with out passing for the creation of a temporary file. This could be skipped if there is some way to pass a variable from the VTE to the python script. Any help on this would be great!
In VTE you use terminal.feed("string")
See vte_terminal_feed.
With python Popen is the suggested method to execute commands.
If you are wanting to use commands then you should do this.
#Uncomment the next line to get the print() function of python 3
#from __future__ import print_function
import os
import subprocess
from subprocess import Popen
command = "echo \"something\""
env = os.environ.copy()
try:
po = Popen(command, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE,
universal_newlines=True, env=env)
po.wait()
output, error_output = po.communicate()
if po.returncode:
print(error_output)
else:
print(output)
except OSError as e:
print('Execution failed:', e, file=sys.stderr)
If you want to use gtk with gtk vte then do this instead.
#place the following in a method of a vte instance
env = os.environ.copy()
try:
po = Popen(command, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE,
universal_newlines=True, env=env)
po.wait()
output, error_output = po.communicate()
if po.returncode:
print(error_output)
else:
self.feed(output) #here you're printing to your terminal.
except OSError as e:
print('Execution failed:', e, file=sys.stderr)
For the finest control in a regular terminal you can try the cmd module. This will require that you produce your own prompt so it is a more specific option to get what you want.

Resources