0

I'm trying to get a label's date. The cmd command that I know is:

p4 labels -e the_label_name

The indeed gives me the following:

Label the_label_name 2014/06/05 00:05:13 'Created by mebel. '

To use python, I wrote:

os.system("sc labels -t -e the_label_name")

and what I got was:

Label the_label_name 2014/06/05 00:05:13 'Created by mebel. '

0

However, if I write

label = os.system("sc labels -t -e the_label_name")

I get that

label = 0

Do you know what am I missing?

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
NimrodB
  • 153
  • 3
  • 13
  • As your first example clearly shows, the return value of the `os.system` call is `0`. This gets assigned to `label`. Per [the documentation](https://docs.python.org/2/library/os.html#os.system), consider using `subprocess` if you want to retrieve the result of the process. – jonrsharpe Jun 15 '14 at 14:36
  • 1
    Consider using the P4Python library; it makes scripting Perforce calls much easier. – Bryan Pendleton Jun 15 '14 at 15:27
  • You could also use the -G global option, which "causes all output (and batch input for form commands with -i) to be formatted as marshalled Python dictionary objects. This is most often used when scripting." See http://www.perforce.com/perforce/doc.current/manuals/cmdref/global.options.html. – Mike O'Connor Jun 16 '14 at 02:04

2 Answers2

0

According to the documentation of os.system, the return value is the exit status of the program.

If you want to retrieve the output of the program, you can use the check_output function from subprocess:

import subprocess
label = subprocess.check_output("sc labels -t -e the_label_name", shell=True)

Example:

>>> import subprocess
>>> subprocess.check_output("shuf -n 1 /usr/share/dict/words", shell=True)
>>> 'monkey-pot\n'
eskaev
  • 1,108
  • 6
  • 11
  • I tried this and got: `Traceback (most recent call last): File "", line 1, in File "/org/seg/tools/freeware/python/2.7.1/1/el-5-x86_64/lib/python2.7/subprocess.py", line 530, in check_output process = Popen(stdout=PIPE, *popenargs, **kwargs) File "/org/seg/tools/freeware/python/2.7.1/1/el-5-x86_64/lib/python2.7/subprocess.py", line 672, in __init__ errread, errwrite) File "/org/seg/tools/freeware/python/2.7.1/1/el-5-x86_64/lib/python2.7/subprocess.py", line 1202, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory ` – NimrodB Jun 16 '14 at 12:25
  • Right, you should use `shell=True`, or pass the command as a list of strings: `['sc', 'labels', '-t', '-e', 'the_label_name']`. – eskaev Jun 16 '14 at 17:49
0

I found this:

label = os.popen("sc labels -e the_label_name")
label = label.read()

That fixed everything...

NimrodB
  • 153
  • 3
  • 13