python print a string in array format - python

I passed an argument to a python script like -b bench. The bench is created like this:
bench_dir = '~/myFD/'
bench_bin = bench_dir + 'src/bin/Assembler'
bench_inp1 = bench_dir + 'input/in.fa'
bench_out1 = bench_dir + 'output/data.scratch'
bench= LiveProcess()
bench.executable = bench_bin
bench.cwd = bench_dir
bench.cmd = [bench.executable] + ['-s', bench_out1, '<', bench_inp1]
The bench.cmd should looks like:
~/myFD/src/bin/Assembler -s ~/myFD/output/data.scratch < ~/myFD/input/in.fa
to do that, I use print bench.cmd but it doesn't show the above statment correctly. Instead it shows:
['~/myFD/src/bin/Assembler', '-s', '~/myFD/output/data.scratch', ' < ', '~/myFD/input/in.fa']
how can I fix that?

Try: print ' '.join(bench.cmd). This joins the list and uses a space as delimiter

You could do ' '.join(bench.cmd).

case for join: ' '.join(bench.cmd)

Are you looking for this,
>>> mylist = ['~/myFD/src/bin/Assembler', '-s', '~/myFD/output/data.scratch', ' < ', '~/myFD/input/in.fa']
>>> " ".join(mylist)
'~/myFD/src/bin/Assembler -s ~/myFD/output/data.scratch < ~/myFD/input/in.fa'
or just concatenate your strings
bench.cmd = bench.executable + ' -s ' + bench_out1 + ' < ' + bench_inp1

Related

Python 3: Making a new line in a variable

I'm currently trying to make an ASCII map via python using segments of walls. I got it to work in print() but I'm a bit new and don't know how to store it to a variable.
If I invoke the variable, it prints the list with no line breaks. If I assign a variable to a print, it works, but prints it all first before I want it to.
Any solutions? Can I format the initial a1_map list to create the new lines?
Here's what I have:
north_exit = ' ___| |___'
north_no_exit = ' ___________'
south_exit = ' ```| |``` '
mid_no_exit = '| |'
top_WandE_exit = '\u2143 L'
top_W_exit = '\u2143 |'
top_E_exit = '| L'
mid_WandE_exit = ' (\u00B0.\u00B0) '
mid_W_exit =' (\u00B0.\u00B0) |'
mid_E_exit ='| (\u00B0.\u00B0) '
lower_W_exit = '\u02E5 |'
lower_WandE_exit = 'T T'
lower_E_exit = '| T'
current_room = 'the crew quarters'
a1_map = print(north_no_exit,'\n' + top_E_exit,'\n' + mid_E_exit,'\n' + lower_E_exit, '\n' +south_exit, '\n'+ 'You are in',current_room+'.')
I could just type:
print(north_no_exit,'\n' + top_E_exit,'\n' + mid_E_exit,'\n' + lower_E_exit, '\n' +south_exit, '\n'+ 'You are in',current_room+'.')
each time. However I want to format it so I can just type:
print(a1_map)
As an example, the list output without print() looks like:
(' ___________', '\n| L', '\n| (°.°) ', '\n| T', '\n | | ', '\nYou are in', 'the crew quarters.')
I would like it to look like (as an example):
___________
| L
| (°.°)
| T
```| |```
(EDIT: Sorry, trying to make it look like a box but I cant even do it on here!)
So, I feel dumb.
Formatting it and then using a loop seemed to work
a1_map = [north_no_exit, top_E_exit, mid_E_exit, lower_E_exit, south_exit]
for segment in a1_map:
print(segment)
You can simply use + to join strings or string join() method to join them with a separator string.
You can also make a dictionary or a list to help you manage them and iterate them
I think you can use Python's f-string.
north_exit = ' ___| |___'
north_no_exit = ' ___________'
south_exit = ' ```| |``` '
mid_no_exit = '| |'
top_WandE_exit = '\u2143 L'
top_W_exit = '\u2143 |'
top_E_exit = '| L'
mid_WandE_exit = ' (\u00B0.\u00B0) '
mid_W_exit =' (\u00B0.\u00B0) |'
mid_E_exit ='| (\u00B0.\u00B0) '
lower_W_exit = '\u02E5 |'
lower_WandE_exit = 'T T'
lower_E_exit = '| T'
current_room = 'the crew quarters'
a1_map = f"{north_no_exit}\n{top_E_exit}\n{mid_E_exit}\n{lower_E_exit}\n{south_exit}\n"
message = "You are in',current_room."
print(a1_map+message)

How to save list, dict, int into file, and assign back from file

I have an PYQT5 UI with that allow user to store values into list, int, and qttextedit (allow user to write as code editor.
Then i save existing values into txt file, so after user changed values can always come back and reload from the local file. The problem i face is when i assign back, it became a letter by letter, even the code assign back into UI will have \n. I also tried turn them into a list, but result still bad.
So i think save into a txt is a bad idea, I looked for pickle but not sure if it can be used or how to use in this case.
score = 22
ocount = 88
scenario = {something here already}
...
usercode = 'var game = 0;\n if (game > 3){gid = 22}'
#List, int, dict, str store to txt file
with open(configName + ".txt", 'w') as f:
f.write(repr(score) + "\n" + \
repr(ocount) + "\n" + \
repr(option) + "\n" + \
repr(option_ans) + "\n" + \
repr(matchname) + "\n" + \
repr(scenario) + "\n" + \
repr(_Options) + "\n" + \
repr(_Optionselected) + "\n" + \
repr(eInfo) + "\n" + \
repr(sVar) + "\n" + \
repr(cusotm) + "\n" + \
repr(survey1) + "\n" + \
repr(survey_ans) + "\n" + \
repr(eInfoName) + "\n" + \
repr(sVarName) + "\n" + \
repr(tempcode) + "\n" + \
repr(usercode))
The value output as below:
2
1
['q1_a1', 'q1_a2', 'q2_a1']
['q1_a1_ans', 'q1_a2_ans', 'q2_a1_ans']
['log1', 'log2']
{'log1': 'if (q1_a1) scores.team1 - 1q1_a1_ans== "23234"){\nproduct_ids = [11,22];\n}', 'log2': 'if (scores.team2 != 11\nproduct_ids = [33,2];\n}'}
['var q1_a1 = 11;', 'var q1_a2 = 11122;', 'var q2_a1 = 2;']
['var q1_a1_ans = 22;', 'var q1_a2_ans = 222;', 'var q2_a1_ans = 2;']
['123']
['321']
['cam1']
['q1_a1', 'q1_a2', 'q2_a1']
['q1_a1_ans', 'q1_a2_ans', 'q2_a1_ans']
['123']
['321']
'+ + \nelse if (\nelse if (\nelse if (\nelse if ('
'var has_answer = function (answer) {\n return indexOf(answer) >= 0;\n };'
#Load back
tmp=[]
f = open("lo.txt", "r")
Lines = f.readlines()
for x in Lines:
tmp.append(x)
score = tmp[0]
ocount = tmp[1]
etc...
Result:
#try change to list
['[', "'", 'q', '1', '_', 'a', '1', "'", ',', ' ', "'", 'q', '1', '_', 'a', '2', "'", ',', ' ', "'", 'q', '2', '_', 'a', '1', "'", ']', '\n']
use exec() to execute string as code
var = ['score', 'option', 'tempcode', 'usercode']
f = open("lo.txt", "r")
Lines = f.readlines()
for i in range(0, len(Lines)):
exec(f'{var[i]} = {Lines[i]}')
# check type
exec(f'print({var[i]}, type({var[i]}))')
output
2 <class 'int'>
['q1_a1', 'q1_a2', 'q2_a1'] <class 'list'>
+ +
else if (
else if (
else if (
else if ( <class 'str'>
var has_answer = function (answer) {
return indexOf(answer) >= 0;
}; <class 'str'>
lo.txt
2
['q1_a1', 'q1_a2', 'q2_a1']
'+ + \nelse if (\nelse if (\nelse if (\nelse if ('
'var has_answer = function (answer) {\n return indexOf(answer) >= 0;\n };'
Or write them in json instead, make sure list is still list.

Python self defined function with None argument

I want to define my own function as below:
def myown(df, ADD1, ADD2 = None, OtherArgument_1, OtherArgument_2):
tmp = df
tmp['NEWADD'] = (tmp['ADD1'] + ' ' + tmp['ADD2']).str.strip()
return tmp
I know this is incorrect so I can add if statement in the function.
def myown(df, ADD1, ADD2 = None, OtherArgument_1, OtherArgument_2):
tmp = df
if ADD2 == None:
tmp['NEWADD'] = tmp[ADD1].str.strip()
else:
tmp['NEWADD'] = (tmp[ADD1] + ' ' + tmp[ADD2]).str.strip()
However, If I don know how many ADD inputs at first, how can I modify this?
For example, there are 5 ADD need to be combined this time and next time it may be 3. It is difficult to re-write function each time like this:
def myown(df, ADD1, ADD2, ADD3, ADD4, ADD5, OtherArgument_1, OtherArgument_2):
tmp = df
tmp['NEWADD'] = (tmp[ADD1] + ' ' + tmp[ADD2] + ' ' + tmp[ADD3] + ' ' + tmp[ADD4] + ' ' + tmp[ADD5]).str.strip()
You can accomplish this by using loops and lists like this:
def myown(df, add_args, OtherArgument_1, OtherArgument_2):
tmp = df
new_add = ''
for i in add_args:
new_add = new_add + tmp[i].str.strip() + ''
tmp['NEWADD'] = new_add
Your add_args parameter must be a list, which looks like this:
add_args = [ADD1, ADD2, ADDn]

Python script with subprocess returns must be str, not int evrything linter says this is the case [duplicate]

This question already has an answer here:
How can I concatenate str and int objects?
(1 answer)
Closed 4 years ago.
I get the following error when i run the following code.
Version info:
Python 3.6.5 (default, May 11 2018, 04:00:52) [GCC 8.1.0] on linux
Code:
Proper format at https://gist.github.com/Drunkenpanda2000/31f76521ce1166b804a539f40ec21c60
#!/usr/bin/env python
import subprocess
#will be replaced with inputs from Chef
name='test'
vcpus=1
memory=2048
iso='/var/lib/libvirt/images/Centos.iso'
discsize= 80
os_type='linux'
os_variant='centos7'
network_bridge='default'
#setting up the command
args = (
'virt-install' +
' --name=' + name +
' --vcpus=' + vcpus +
' --memory=' + memory +
' --cdrom=' + iso +
' --disk size=' + discsize +
' --os-type=' + os_type +
' --os-varient=' + os_variant +
' --network bridge=' + network_bridge +
" --extra-args 'console=ttyS0,115200n8 serial'" )
#execute the commands in bash
subprocess.call(args, shell=True)
Error
[drunkenpanda#Diablo Scripts]$ ./createvm.py Traceback (most recent call last): File "./createvm.py", line 27, in <module>
' --network bridge=' + network_bridge + TypeError: must be str, not int
New code
args = ['virt-install',
' --name',name,
' --vcpus',str(vcpus),
' --memory',str(memory),
' --cdrom',iso,
' --disk-size',str(discsize),
' --os-variant',os_variant,
' --os-type',os_type,
' --network bridge',network_bridge]
# " --extra-args 'console=ttyS0,115200n8 serial'"\
#execute the commands in bash
subprocess.call(args, shell=False)
New error
./createvmattend.1.py
usage: virt-install --name NAME --memory MB STORAGE INSTALL [options]
virt-install: error: unrecognized arguments: --name bob --vcpus 1 --memory 2048 --cdrom /var/lib/libvirt/images/Centos.iso --disk-size 80 --os-variant centos7.0 --os-type linux --network bridge virbr0
You can only string-concatenate strings, not integers.
Crude but should work:
args = (
'virt-install' +
' --name=' + name +
' --vcpus=' + str(vcpus) + # fix
' --memory=' + str(memory) + # fix
' --cdrom=' + iso +
' --disk size=' + str(discsize) + # fix
' --os-type=' + os_type +
' --os-varient=' + os_variant +
' --network bridge=' + network_bridge +
" --extra-args 'console=ttyS0,115200n8 serial'" )
If you are on python 3.6 you might want to switch to Literal String Interpolation PEP-498:
someValue = 22
c = f"This text contains {someValue}"
or you can use .format()
someValue = 22
c = "This text contains {}".format(someValue) # positional replacement of {} by var

Scripting Python for Linux commands

I have a question. I have been really trying to learn Python. For a project, I want to make an ncurses GUI for my backup server. My backup server runs rdiff-backup, and I want to have the ncurses take in variable names and plug them into my script. I have been trying to do a lot of reading so I don't ask dumb questions.
Here is my function for running the script:
def runScript():
# Cannot concatenate 'str' and 'list' objects
#script = rdiff + rdiffArgs
script = rdiff + ' ' + rdiffVerbosity + ' ' + rdiffStatistics \
+ ' ' + clientName + '#' + clientHost + '::' + clientDir \
+ ' ' + serverDir
os.system(script)
What I originally thought would be neat was to add all the variables into a list, so I could just run say
script = rdiff + rdiffArgs
Is there a better way to do this without all the space concatenation?
Thanks for your assistance
EDIT: Let me post the whole script so far. I wasn't very clear and I really appreciate your help and patience
#!/usr/bin/env python
import os
import smtplib
# Global variables
rdiff = '/usr/bin/rdiff-backup'
rdiffVerbosity = '-v5'
rdiffStatistics = '--print-statistics'
emailSmtp = 'smtp.gmail.com'
smtpPort = '465'
emailUsername = 'reports'
emailPassword = '3kc9dl'
emailTo = 'user#domain.com'
emailFrom = 'internal#domain.com'
serverName = 'root'
serverHost = 'SV-Datasafe'
serverDir = '/srv/backup/SV-Samba01'
clientName = 'root'
clientHost = 'SV-Samba01'
clientDir = '/srv'
rdiffArgs = rdiffArgs = [rdiffVerbosity, rdiffStatistics, \
clientName + '#' + clientHost + '::' \
+clientDir + ' ' + serverDir]
time = ''
dateStamp = datetime.now()
def sendEmail():
subject = dateStamp + clientName
body = clientDir + ' on ' + clientHost + ' backed up to ' + serverName + \
' in the directory ' + serverDir + ' on ' + dateStamp
message = """\
From: %s
To: %s
Subject: %s
%s
""" % (emailFrom, emailTo, subject, body)
deliverEmail = smtplib.SMTP(emailSmtp, port=smtpPort)
deliverEmail.login(emailUsername, emailPassword)
def runScript():
# Cannot concatenate 'str' and 'list' objects
#script = rdiff + rdiffArgs
script = rdiff + ' ' + rdiffVerbosity + ' ' + rdiffStatistics \
+ ' ' + clientName + '#' + clientHost + '::' + clientDir \
+ ' ' + serverDir
os.system(script)
# TODO:: Logging
you can use format specifiers
def runScript():
script = "%s %s %s#%s %s::%s %s" %(rdiff,rdiffVerbosity,rdiffStatistics,clientName,clientHost,clientDir,serverDir)
os.system(script)
or say your rdiffArgs is already in a list
rdiffArgs = [rdiffVerbosity,rdiffStatistics,clientName,clientHost,clientDir,serverDir]
you can join them with a space
rdiffArgs = ' '.join(rdiffArgs)
lastly, just so you might want to know, you can import rdiff in your script , since rdiff-backup is written in Python
from rdiff_backup.Main import Main as backup
task=['/etc', '/tmp/backup']
backup(task)
the above backs up /etc/ to /tmp/backup. That way, you don't have to make system call to rdiff-backup. Of course, this is up to you. making system call is sometimes easier
try to use subprocess module and pass arguments as list e.g.
client = clientName + '#' + clientHost + '::' + clientDir
cmd = [rdiff, rdiffVerbosity, rdiffStatistics, client , serverDir]
p = Popen(cmd ", shell=True)
print os.waitpid(p.pid, 0)[1]
or if have args already as list use something like this
cmd = [rdiff] + args
You join paths using os.path.join
You concatenate strings like so: "".join(['a', 'b']) or ", ".join(['c', 'd'])
Which part is difficult? I am not sure I understand the question 100%
Is this it?
script = rdiff + " ".join(rdiffArgs)

Categories

Resources