I write a function which sets system time in linux. I write next code:
import time
import subprocess
def SetSystemTime(val):
try:
val = float(val)
except ValueError:
return
command = 'date -s"' + time.ctime(val) + '"'
subprocess.call(command)
On calling of that i get:
File "crc.py", line 96, in
SetSystemTime(0)
File "crc.py", line 12, in SetSystemTime
subprocess.call(command)
File "/usr/lib/python2.7/subprocess.py", line 493, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.7/subprocess.py", line 679, in init
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1239, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
subprocess.call() normally takes a list of strings as its first argument. If you hand it a string X (as you do), that one will be converted to list with that whole string as its first argument.
The first element of that list is executed with the rest of that list as arguments.
So the underlying OS tries to execute the executable 'date -s"XXYYXXZ"' and cannot find it.
This is different from os.system() that hands the parameter to a shell that most often splits the string it gets at the spaces and then executes the first element split off.
Try:
command = ['date', '-s"' + time.ctime(val) + '"']
subprocess.call(command)
as the last two lines.
Related
Using python 2.7 with mmap to perform http upload, encountered runtime exception with:
fdata = fp.read()
TypeError: read() takes exactly 1 argument (0 given)
Here's the code :
import requests
dcs_session = requests.Session()
with open(filename, 'rb') as f:
with contextlib.closing(mmap.mmap(f.fileno(), 0,
access=mmap.ACCESS_READ)) as mmap_obj:
resp = dcs_session.post(url, headers=additional_headers,
data=form_data,files={'file': mmap_obj}, timeout=1000, verify=verify_arg)
Here's the Exception :
fdata = fp.read()
TypeError: read() takes exactly 1 argument (0 given)
ERROR (/usr/bin/dca.py:563 : dcs_push Stack trace - Traceback (most recent call last):
File "/usr/bin/dca.py", line 540, in dcs_push
verify=verify_arg)
File "/usr/lib/python2.7/site-packages/requests/sessions.py", line 555, in post
return self.request('POST', url, data=data, json=json, **kwargs)
File "/usr/lib/python2.7/site-packages/requests/sessions.py", line 494, in request
prep = self.prepare_request(req)
File "/usr/lib/python2.7/site-packages/requests/sessions.py", line 437, in prepare_request
hooks=merge_hooks(request.hooks, self.hooks),
File "/usr/lib/python2.7/site-packages/requests/models.py", line 308, in prepare
self.prepare_body(data, files, json)
File "/usr/lib/python2.7/site-packages/requests/models.py", line 496, in prepare_body
(body, content_type) = self._encode_files(files, data)
File "/usr/lib/python2.7/site-packages/requests/models.py", line 159, in _encode_files
fdata = fp.read()
TypeError: read() takes exactly 1 argument (0 given)
mmap's read method required you to pass an argument prior to Python 3.3. It's not a drop-in replacement for a file object, and even if it was, it wouldn't do any good to use it, because the read method is making a copy anyway, so you're not avoiding any allocated memory usage. Just pass the file object instead of mmaping it, or upgrade to modern Python (Python 2 has been out of support for well over a year; stop writing new code in it).
I need to use a file as argument to the command but subprocess.call returns following error
>>> with open('test.txt') as F:
... subprocess.call(['cat', F])
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/usr/lib64/python2.7/subprocess.py", line 524, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib64/python2.7/subprocess.py", line 711, in __init__
errread, errwrite)
File "/usr/lib64/python2.7/subprocess.py", line 1327, in _execute_child
raise child_exception
TypeError: execv() arg 2 must contain only strings
However when file is not stored as variable it works fine
>>> subprocess.call(['cat', 'test.txt'])
fruit=banana
fruit=mango
fruit=apple
0
Code with open('test.txt') as F opens the file and assigns its pointor to variable F.
If I understand correctly you wanted file's content. Since subprocess.call required a command like you execute from terminal/console(In your case cat test.txt). Here in the subprocess.call you are passing File Descriptor sometime called File Pointer instead of file itself.
Therefore from the code if you really want a file content, you can simply use F.read() or F.readlines(). For Example
with open('test.txt') as F:
print F.readlines()
Also note that subprocess.call expect arguments as string. In the first case its the file object i.e <open file 'test.txt', mode 'r' at 0x7fa64a6f5a50> that leads to a traceback whereas in the second case its string i.e test.txt that's why works without any issue.
Here is the code:
name = input("Enter Molecule ID: ")
name_in = name+'.lac.dat'
print(name_in)
atm_chg = []
with open(name_in) as f:
# skip two lines
f.readline()
f.readline()
for line in f.readlines():
atm_chg.append(float( line.split()[-1] ))
This is to process input for a larger Python program.
The input is:
LOEWDIN ATOMIC CHARGES
----------------------
0 C : -0.780631
1 H : 0.114577
2 Br: 0.309802
3 Cl: 0.357316
4 F : -0.001065
Finally the runtime messages are:
runfile('/home/comp/Apps/Python/Testing/ReadFile_2.py', wdir='/home/comp/Apps/Python/Testing')
Enter Molecule ID: A
A.lac.dat
Traceback (most recent call last):
File "<ipython-input-1-8c665940b39f>", line 1, in <module>
runfile('/home/comp/Apps/Python/Testing/ReadFile_2.py', wdir='/home/comp/Apps/Python/Testing')
File "/home/comp/Apps/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 866, in runfile
execfile(filename, namespace)
File "/home/comp/Apps/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "/home/comp/Apps/Python/Testing/ReadFile_2.py", line 27, in <module>
atm_chg.append(float( line.split()[-1] ))
IndexError: list index out of range
In spite of the errors there is an entry in the Variable Explorer (Spyder IDE):
[-0.780631, 0.114577, 0.309802, 0.357316, -0.001065]
which is exactly what I require.
The program is probably crashing because it's trying to process an empty line beyond the last line of data. You can fix this by making sure the line is non-empty before processing it:
for line in f.readlines():
if line.strip(): # is the line non-empty, ignoring white space
atm_chg.append(float( line.split()[-1] ))
from a Python script I want to call a few external programs and use their output inside the script. Now I found that this script is running on my local system, but gets problems on another one that uses another language. So instead of checking the output in different languages, I want to call these programs with a specified "LC_ALL=en_US.utf8" as first argument. But it seems that subprocess does not like this:
lc = "LC_ALL=en_US.utf8"
uptimedata = subprocess.check_output([lc, "/bin/uptime"])
When I run the script, I get:
Traceback (most recent call last):
File "./serverwatch.py", line 22, in <module>
uptimedata = subprocess.check_output([lc, "/bin/uptime"])
File "/usr/lib/python2.7/subprocess.py", line 537, in check_output
process = Popen(stdout=PIPE, *popenargs, **kwargs)
File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1259, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
I understand that subprocess.check_output() wants the first argument to be the command to be called. So how can I run the command with the changed LC?
This is Python 2.7.3 on Debian Wheezy. The other system is running the same versions.
Execute your command through bash:
>>> lc = "LC_ALL=en_US.utf8"
>>> command = ["/usr/bin/bash", "-c", "%s /bin/uptime" % lc]
>>> command
['/usr/bin/bash', '-c', 'LC_ALL=en_US.utf8 /bin/uptime']
>>> uptimedata = subprocess.check_output(command)
>>> uptimedata
b' 13:26:01 up 17:43, 1 user, load average: 0.36, 0.41, 0.44\n'
>>>
I've been using both for a while to interface with AWS in different computers without issue until now. For some reason, in one of my machines I keep getting "TypeError: sequence item 0: expected string, int found" on boto.connect_s3 operations related to buckets.
I'm able to connect to my S3 without issues, but if I try to create a new bucket, retrieve a specific bucket or anything related to buckets, I get that error. Also, this only happens in one out of my three computers.
Any help would be appreciated.
Edit I was having the error in python 2.7.9 32 bit. I installed 2.7.9 64 bit and seems to be working fine.
This is the code I'm using, it works fine on other machines.
import boto
conn = boto.connect_s3()
conn.create_bucket("gbatestingbucket2")
This is the error I get:
Traceback (most recent call last):
File "C:\Users\Sunpower\Desktop\EC2Automation\test.py", line 4, in <module>
conn.create_bucket("gbatestingbucket2")
File "c:\Python27\lib\site-packages\boto\s3\connection.py", line 612, in create_bucket
data=data)
File "c:\Python27\lib\site-packages\boto\s3\connection.py", line 664, in make_request
retry_handler=retry_handler
File "c:\Python27\lib\site-packages\boto\connection.py", line 1070, in make_request
retry_handler=retry_handler)
File "c:\Python27\lib\site-packages\boto\connection.py", line 942, in _mexe
request.body, request.headers)
File "c:\Python27\lib\httplib.py", line 946, in request
self._send_request(method, url, body, headers)
File "c:\Python27\lib\httplib.py", line 986, in _send_request
self.putheader(hdr, value)
File "c:\Python27\lib\httplib.py", line 924, in putheader
str = '%s: %s' % (header, '\r\n\t'.join(values))
TypeError: sequence item 0: expected string, int found
[Finished in 0.5s with exit code 1]